我想做的是:当我点击一个元素时,它将所有子元素克隆到另一个 div 并滚动到我点击的 div 的克隆。
为此,我将类 vp
添加到单击对象的克隆中。那很好用。然后我添加了这个来滚动到那个元素:
var target = output.find(".vp");
$(".output").animate({
scrollLeft: target.offset().left
}, 500);
但这行不通。第一次点击时,它工作正常,但之后它滚动到没有 .vp
类的元素。
这是一个片段。有谁知道我做错了什么?
var output = $(".output div");
$(".wrapper div").click(function(){
var size = $(".wrapper div").length;
output.css('width', size * 100 + 'vw');
var index = $(this).index() + 1;
output.empty();
$(".wrapper div").each(function(){
$(this).removeClass("vp");
$(this).clone().appendTo(output);
});
$(".output div div:nth-child(" + index + ")").addClass("vp");
setTimeout(function(){
var target = output.find(".vp");
$(".output").animate({
scrollLeft: target.offset().left
}, 500);
}, 10);
});
body{
width:100vw;
overflow:hidden;
margin:0;padding:0;
}
.wrapper{
height:100%;
width:100vw;
background:none;
}
.wrapper div{
float:left;
height:100px;
width:100px;
background-color: #a0a0a0;
margin:10px;
cursor:pointer;
}
.output{
font-size:2em;
height:200px;
width:100vw;
display:block;
overflow-x:auto;
overflow-y:hidden;
}
.output div{
height:200px;
width:100vw;
}
.output div div{
position:relative;
display:block;
float:left;
width:100vw;
height:200px;
}
.vp{
background-color:#a0a0a0;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="output">
<div></div>
</div>
最佳答案
像这样改变你的功能
$(".output").animate({
scrollLeft: target.width() * (index-1)
}, 500);
var output = $(".output div");
$(".wrapper div").click(function(){
var size = $(".wrapper div").length;
output.css('width', size * 100 + 'vw');
var index = $(this).index() + 1;
output.empty();
$(".wrapper div").each(function(){
$(this).removeClass("vp");
$(this).clone().appendTo(output);
});
$(".output div div:nth-child(" + index + ")").addClass("vp");
setTimeout(function(){
var target = output.find(".vp");
$(".output").animate({
scrollLeft: target.width() * (index-1)
}, 500);
}, 10);
});
body{
width:100vw;
overflow:hidden;
margin:0;padding:0;
}
.wrapper{
height:100%;
width:100vw;
background:none;
}
.wrapper div{
float:left;
height:100px;
width:100px;
background-color: #a0a0a0;
margin:10px;
cursor:pointer;
}
.output{
font-size:2em;
height:200px;
width:100vw;
display:block;
overflow-x:auto;
overflow-y:hidden;
}
.output div{
height:200px;
width:100vw;
}
.output div div{
position:relative;
display:block;
float:left;
width:100vw;
height:200px;
}
.vp{
background-color:#a0a0a0;
left:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="output">
<div></div>
</div>
关于javascript - jQuery - 滚动到具有动态类的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48440712/