2016-03-10 47 views
0

我想在頁面加載時連續左右移動div。但我所做的是繼續點擊。這就是我不想要的。這裏是我的代碼:移動div右jquery連續不斷

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
 
<body> 
 

 
<a href="" class="left">left</a> | <a href="" class="right">right</a> 
 
<br /><br /> 
 
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div> 
 

 
<script> 
 
$('.right').click(function(e) { 
 
    e.preventDefault(); 
 
    $('#foo').css({ 'right': '0px', 'left': '' }).animate({ 
 
     'right' : '30px'  
 
    });      
 
}); 
 

 
$('.left').click(function(e) { 
 
    e.preventDefault(); 
 
    $('#foo').css({ 'right': '', 'left': '0px' }).animate({ 
 
     'left' : '30px' 
 
    });      
 
}); 
 
</script>

回答

0

auto值不會自動正確的jQuery或瀏覽器分配。

使用這樣的事情:

$('.right').click(function(e) { 
 
    e.preventDefault(); 
 
    $('#foo').css({ 'right': window.innerWidth - $('#foo').position().left - $('#foo').width(), 'left': 'auto' }).animate({ 
 
    'right' : '30px' 
 
    }); 
 
}); 
 

 
$('.left').click(function(e) { 
 
    e.preventDefault(); 
 
    $('#foo').css({ 'left': $('#foo').position().left, 'right': 'auto' }).animate({ 
 
    'left' : '30px' 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
 
<a href="" class="left">left</a> | <a href="" class="right">right</a> 
 
<br /><br /> 
 
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div>

至於你的問題說,如果你想讓它做自動兩種,在頁面加載,這樣做:

$(function() { 
 
    function a() { 
 
    $('#foo').css({ 'right': window.innerWidth - $('#foo').position().left - $('#foo').width(), 'left': 'auto' }).animate({ 
 
     'right' : '30px' 
 
    }, function() { 
 
     $('#foo').css({ 'left': $('#foo').position().left, 'right': 'auto' }).animate({ 
 
     'left' : '30px' 
 
     }, a); 
 
    }); 
 
    } 
 
    a(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> 
 
<br /><br /> 
 
<div id="foo" style="background:red;width:100px;height:100px;position:absolute"></div>

0

您可以CSS animation

#foo { 
 
    background: red; 
 
    width: 100px; 
 
    height: 100px; 
 
    position: absolute; 
 
    left: 0; 
 
    animation: leftRight linear 3s infinite alternate; 
 
    
 
} 
 

 
@keyframes leftRight { 
 
    to { 
 
    left: 100%; 
 
    transform: translateX(-100%); 
 
    } 
 
}
<div id="foo"></div>

做到這一點