简体   繁体   中英

Onclick slider in pure JavaScript - event doesn't changes CSS value

Im trying to make some kind of slider in pure JavaScript (I can't use jQuery or other frameworks because it is for eBay).

I have function like that:

var slider_moves = 0;
var imagecount = document.querySelectorAll(".slides_gsc > img").length;
var slide = document.getElementsByClassName('slider_img_width').offsetWidth;

    function slideLeft(){
        if(slider_moves < imagecount -1){
            document.getElementsByClassName("slides_gsc").style.right +=slide; //for me this is not working
            slider_moves++;
        }
    };

Why it is not working? I can't use += or variable to change an CSS value?

There are several problems. As has been pointed out in other answers, the document.getElementsByClassName() function will return a node list, which you need to iterate through. Also the right attribute typically contains a unit (unless its value is something like inherit or auto ). Assuming you're working with pixels (since you're assigning a pixel value to slide ) you could do something like this:

 var slide = document.getElementsByClassName('slider_img_width')[0].offsetWidth;

and then

 var elements = document.getElementsByClassName("slides_gsc"); 
 for(var i=0;i<elements.length;i++){
     slider_moves++;
     elements[i].style.right = (slide*slider_moves)+"px";
 }    
getElementsByClassName("slides_gsc")

will return an array that you will have to loop through, if you know for sure there is only 1 elem with that class use

getElementsByClassName("slides_gsc")[0]

or use an Id on the element. if there is more than 1 element use

 var elems=document.getElementsByClassName("slides_gsc"); 
 for(var i=0;i<elems.length;i++){
     elems[i].style.right+=slide;
        slider_moves++;
 }    

According to icke's answer I done code like that and it's working:

var slider_moves = 0;
var imagecount = document.querySelectorAll(".slides_gsc img").length;
var slide = document.getElementsByClassName('slider_img_gsc')[0].offsetWidth;

    function slideLeft(){
        if(slider_moves < imagecount -1){
            slider_moves++;
            document.getElementsByClassName("slides_gsc")[0].style.right = (slide*slider_moves)+"px";
        }
    };

Of course it's called by:

<div class="right_navigation_gsc navigation_gsc" onclick = "slideRight()"></div>

Thanks a lot all of you ;)

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