我的目标是每次单击按钮时,将框沿“X”轴平移
100px
。我通过在 jQuery 中使用 temp
变量以某种方式使它成为可能。
是否有任何其他方法可以纯粹通过 CSS 来实现,这样当单击按钮时,框应该从当前位置 translate
100px
?
var temp = 100;
$(document).ready(function(){
$('#b1').click(function(){
$('#box-one').css("transform","translate("+temp+"px, 0px)");
temp = temp + 100;
});
});
#box-one
{
background-color: blue;
height: 100px;
width: 100px;
transition: all 0.3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="box-one"></div>
<button id="b1">Move</button>
</body>
</html>
最佳答案
这里是一个纯CSS的方法,虽然有点疯狂。
根据需要添加更多输入(和关联的 CSS):
html, body {
margin: 0;
padding: 0;
}
#box-one {
background-color: blue;
height: 100px;
width: 100px;
transition: all 0.3s ease;
}
input[type=checkbox] {
position: absolute;
opacity: 0;
transform: scaleX(7) scaleY(2);
top: 100px;
}
input:first-of-type {z-index: 1;}
input:checked {display: none;}
input:checked + input {z-index: 1}
input:checked:nth-child(1) ~ #box-one {transform: translateX(100px);}
input:checked:nth-child(2) ~ #box-one {transform: translateX(200px);}
input:checked:nth-child(3) ~ #box-one {transform: translateX(300px);}
input:checked:nth-child(4) ~ #box-one {transform: translateX(400px);}
input:checked:nth-child(5) ~ #box-one {transform: translateX(500px);}
input:checked:nth-child(6) ~ #box-one {transform: translateX(600px);}
input:checked:nth-child(7) ~ #box-one {transform: translateX(700px);}
input:checked:nth-child(8) ~ #box-one {transform: translateX(800px);}
input:checked:nth-child(9) ~ #box-one {transform: translateX(900px);}
input:checked:nth-child(10) ~ #box-one {transform: translateX(1000px);}
<input type="checkbox"><input type="checkbox"><input type="checkbox"><input type="checkbox"><input type="checkbox">
<input type="checkbox"><input type="checkbox"><input type="checkbox"><input type="checkbox"><input type="checkbox">
<div id="box-one"></div>
<button>Move</button>
关于jquery - 每次相对于当前位置翻译一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29568928/