我在同一页面上有两个不同的div需要以完全相同的方式滚动内容。我当前的代码运行良好,但可能有更好的方法来实现这一点。我只是不知道如何告诉jQuery在#container-1中使用#move-1而在同一个函数中使用#move-2#container-2。谁能告诉我怎么做?
HTML
<div id="container-1" class="container">
<div class="item item-1">container 1 - item 1</div>
<div class="item item-2">container 1 - item 2</div>
<div class="item item-3">container 1 - item 3</div>
</div>
<button id="move-1">Move item in container 1</button>
<div id="container-2" class="container">
<div class="item item-1">container 2 - item 1</div>
<div class="item item-2">container 2 - item 2</div>
<div class="item item-3">container 2 - item 3</div>
</div>
<button id="move-2">Move item in container 2</button>
的jQuery
$( "#move-1" ).click(function()
{
$( "#container-1 .item" ).animate({ "top": "-=200px" }, "slow" );
});
$( "#move-2" ).click(function()
{
$( "#container-2 .item" ).animate({ "top": "-=200px" }, "slow" );
});
CSS
body {
background: #fff;
}
.container {
position: relative;
background-color: #f5f5f5;
width: 240px;
height: 200px;
overflow: hidden;
font-family: arial, sans;
font-weight: bold;
text-align: center;
}
.item {
position: absolute;
width: 190px;
height: 90px;
color: #000;
overflow: auto;
}
.item-1 {
top: 0px;
}
.item-2 {
top: 200px;
}
.item-3 {
top: 400px;
}
button {
margin-bottom: 20px;
}
答案 0 :(得分:0)
您可以使用所点击元素的ID并获取数字
$('[id^="move-"]').on('click', function() {
var id = this.id.split('-').pop();
$('#container-' + id + ' .item').animate({ "top": "-=200px" }, "slow" );
});
答案 1 :(得分:0)