简体   繁体   中英

Applying CSS class to a Javascript

First off I just wanna state that I know next to nothing when it comes to Javascript so forgive me if I use the wrong jargon.

I'm trying to do a layout for tumblr where the sidebar image will change upon refresh. I'm using an existing layout and following another tutorial on how to achieve the effect.

The CSS class for the sidebar is called "side-img".

The CSS from the original layout is as below

<img class="side-img" src="{image:Sidebar Image}">  

From another tutorial, I'm asked to replace it with the following code to get the changing sidebar image working.

<script language="JavaScript">
<!--
 
 
function random_imglink(){
var myimages=new Array()
//specify random images below. You can have as many as you wish
myimages[1]="IMAGE URL"
myimages[2]="IMAGE URL"
myimages[3]="IMAGE URL"
 
 
var ry=Math.floor(Math.random()*myimages.length)
if (ry==0)
ry=1
document.write('<img src="'+myimages[ry]+'" border=0>')
}
random_imglink()
//-->
</script>

The sidebar image does change upon refresh but now it also loses all the CSS class style which has been set for it in the original layout (eg rounded corner, border width, colour etc).

Seeking advice on this. Thanks!

It's because you are creating a new element with

document.write('<img src="'+myimages[ry]+'" border=0>')

and that element is missing the css class that gives it styling.

Try

document.write('<img class="side-img" src="'+myimages[ry]+'" border=0>')

Multiple issues but

<script language="JavaScript">

Isn't valid, there is no language attribute for <script> tags.

Well there is, but it's deprecated .

var myimages=new Array()

It's not recommended to create an array like this, it's preferred to use:

var images = []

If you want to randomly change the src attribute of an image, here's the way to do it:

<img class="side-img" id="random-image">  

<script>
var images = ["1.png", "2.png"]
var index = Math.floor(Math.random() * images.length)

document.querySelector("#random-image").src = images[index]
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM