简体   繁体   中英

How to add the img-responsive class in javascript

I am trying to make a responsive slider for mobile version. Site was developed using angular JS. When I am trying to integrate the JQuery sliders, total site was distubing because of Bootstrap CSS file. So, in that part I founded a plain Javascript code. And in this how to make those images responsive. Below I am adding the code.

    <head>
    <script type="text/javascript">
    var slideimages = new Array() // create new array to preload images
    slideimages[0] = new Image() // create new instance of image object
    slideimages[0].src = "images/slide/1.jpg" // set image object src property to an image's src, preloading that image in the process
    slideimages[1] = new Image()
    slideimages[1].src = "images/slide/2.jpg"
    slideimages[2] = new Image()
    slideimages[2].src = "images/slide/2.jpg"
    </script>
    </head>
    <body>
    <a href="javascript:slidelink()"><img src="firstcar.gif" id="slide" width=100 height=56 /></a>

<script type="text/javascript">

//variable that will increment through the images
var step = 0
var whichimage = 0

function slideit(){
 //if browser does not support the image object, exit.
 if (!document.images)
  return
 document.getElementById('slide').src = slideimages[step].src
 whichimage = step
 if (step<2)
  step++
 else
  step=0
 //call function "slideit()" every 2.5 seconds
 setTimeout("slideit()",2500)
}

function slidelink(){
 if (whichimage == 0)
  window.location = "#"
 else if (whichimage == 1)
  window.location = "#"
 else if (whichimage == 2)
  window.location = "#"
}

slideit()

</script>

To add a class, just use addClass:

slideimages[0].addClass("img-responsive");

Are you just trying to add a class? I don't quite understand your question.

EDITED you simply need to do this:

function slideit(){
 //if browser does not support the image object, exit.
 if (!document.images)
  return
 document.getElementById('slide').src = slideimages[step].src
document.getElementById('slide').className = "img-responsive";
 whichimage = step
 if (step<2)
  step++
 else
  step=0
 //call function "slideit()" every 2.5 seconds
 setTimeout("slideit()",2500)
}

Previous answers are correct but you have to use $ for jQuery:

$(slideimages[0]).addClass("img-responsive");

WIthout jQuery:

slideimages[0].className += "img-responsive";

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