jquery - 每次相对于当前位置翻译一个元素?

标签 jquery html css css-transforms

我的目标是每次单击按钮时,将框沿“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/

相关文章:

html - CSS 主体光标或拖动光标

javascript - setInterval问题(js)

jquery - TagIt 获取值(value)

javascript - jQuery 按键不检测 CTRL + V

php - 需要在桌面和移动设备的列中换行的帮助

html - 没有背景颜色的css3三 Angular 形

html - Bootstrap 中的 7 个相等的列

html - 防止页面尺寸减小时页面内容越界

html - transform,transform-origin 在@keyframes 中不起作用

javascript - 内容不会显示在 jQuery 的切换按钮上