简体   繁体   中英

JQuery suddenly not working

From someone reason, my javascript hasn't been working right. I isolated and cleaned everything up but am stuck with this. Rather then trying to figure out what it is that's causing this (already spent hours on it), I've decided to just figure out a better way. After all, there's more than one way to skin a cat, right? Here's what I'm trying to do. Have something go from 0 width then back to 100% width. It works but for some reason, it goes back to 0 in my app

Jsfiddle: http://jsfiddle.net/THnvz/2/

$(document).ready(function () {
    $(".stretcher").each(function () {
        $(".stretcher")
            .data("origWidth", $(this).width())
            .width(0)
            .animate({
            width: $(this).data("origWidth")
        }, 2000);
    });
});

Just looking for a cleaner simpler way that will work. Any suggestions?

You should use $(this) consistently within the loop.

$(document).ready(function () {
    $(".stretcher").each(function () {
        var $this = $(this);
        $this
            .data("origWidth", $this.width())
            .width(0)
            .animate({
                width: $this.data("origWidth")
            }, 2000);
    });
});

Your original code was animating every stretcher simultaneously with the widths of each other.

You could also use an ordinary variable instead of saving the width in .data() :

$(document).ready(function () {
    $(".stretcher").each(function () {
        var $this = $(this);
        var orig_width = $this.width();
        $this
            .width(0)
            .animate({
                width: orig_width
            }, 2000);
    });
});

You can do this by using only CSS3

Change your CSS to:

.stretcher {
    background-color:red;
    width:100%;
    height:10px;
    animation: firstchange 2s linear;
    -webkit-animation: firstchange 2s linear;
    -moz-animation: firstchange 2s linear;
}

@keyframes firstchange
{
0% {width:100%}
50% {width:0}
100% {width:100%}
}

@-webkit-keyframes firstchange /* Safari and Chrome */
{
0% {width:100%}
50% {width:0}
100% {width:100%}
}

@-moz-keyframes firstchange /* Firefox */
{
0% {width:100%}
50% {width:0}
100% {width:100%}
}

You dont need any JavaScript. This should work

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