Style.width and left doesn't work

时间:2015-11-18 21:00:43

标签: javascript jquery html css

I want to make the effect of a "photo strip" in a menu div with this background

http://3.bp.blogspot.com/_Y_uUwNwvSU8/SJUSQzlYMXI/AAAAAAAAAA8/5IYVcaRaJDA/S660/tira%2Bfotografica.jpg

Im changing the width and left of the div to simulate this effect with javascript/jquery but it doesn't work this way, for now is "onclick" but i want to make it automatically may be with setInterval?

Here's the HTML Code:

<!DOCTYPE html>
<html>
<head>
    <title>Prueba</title>
    <link type = "text/css" rel = "stylesheet" href = "PruebaIndex.css">
    <script type = "text/javascript" src = "jquery-2.1.4.js"></script>
    <script>
        $(document).ready(function(){
            var slider = document.getElementById("#slider");
            var speed = 10;
            $("#slider").click(function(){
                slider.style.width = (slider.style.width+speed)+"px";
                slider.style.left = (slider.style.left-speed)+"px";
            });
        });
    </script>
</head>

<body>
    <div id = "wrapper">
        <div id = "slider">

        </div>
    </div>
</body>
</html>

And here's the CSS Code:

*{
    padding: 0;
    margin: 0;
}

#slider {
    padding: 0;
    margin: 0;
    background-color: black;
    background-image: url("TiraFotografica.PNG");
    background-repeat: repeat;
    width: 800px;
    height: 304px;
    position: relative;
    overflow: hidden;
}

#wrapper {
    width: 800px;
    height: 1000px;
    margin: 0 auto;
    text-align: center;
    overflow: hidden;
}

I tried anothers different ways, like window.onload, putting the code after all in body, trying $(object).width, etc.. the problem is that when i click this doesn't move, then later i'll try to do automatically..

I have another doubt, this menu will get divs inside (options), when i make this div ("#slider") move, those divs moves too (the options)?

EDIT: I added this by DinoMyte

var speed = 10;
$("#slider").click(function(){
    $(this).css("width",(parseInt($(this).css("width").replace("px","")) + speed) + "px");
    $(this).css("left",(parseInt($(this).css("left").replace("px","")) - speed) + "px");
});

Now it works fine, just need to make this automatically without clicks

sorry for my bad english..

1 个答案:

答案 0 :(得分:1)

问题是let labelSize = CGSize(width: 50, height: 20) let label = UILabel(frame: CGRect(origin: CGPoint.zero, size: labelSize)) label.text = "Hello world" let nsText = NSString(string: label.text ?? "") let textAttributes = [NSFontAttributeName: label.font] let textSize = nsText.sizeWithAttributes(textAttributes) if label.frame.width >= textSize.width { print("Text will fit") } else { print("Text won't fit") } 会给你宽度+“px”,因此slider.style.width无法正常工作。您需要先替换“px”。您还需要将当前宽度值解析为整数。

(slider.style.width+speed)

更好的方法:

slider.style.width = parseInt(slider.style.width.replace("px","")) +speed)+"px";

https://fiddle.jshell.net/a2n234eq/6/