html代码:
<button id="btn_right">往右走</button>
<br>
<br>
<button id="btn_left">往左走</button>
<div id="one"></div>
<div id="line"></div>
css代码:
*{
padding: 0;
margin: 0;
}
#one{
width: 100px;
height: 100px;
background-color: #eba;
position: absolute;
left: 0;
top: 100px;
}
#line{
width: 1px;
height: 800px;
background-color: rgb(114, 90, 81);
position: absolute;
left: 800px;
top: 0;
}
button{
position: absolute;
}
js代码:
//左右移动函数,参数direction:1、-1为向左,1为向右;2.需要移动的元素
function move_lr(direction,obj){
clearInterval(move);
//定时器持续移动obj
move = setInterval(function(){
var oldValue = obj.offsetLeft;
var newValue = oldValue + direction * 10;
if(newValue <= 0){
newValue = 0;
}
else if(newValue >= 800){
newValue = 800;
}
obj.style.left = newValue +"px";
if(newValue == 0 || newValue == 800){
clearInterval(move);
}
},30);
}
//右拐
function right_fun(){
move_lr(1,one);
//尝试把右拐按钮一同移动
move_lr(1,btn_right);
}
//左拐
function left_fun(){
move_lr(-1,one);
}
//监听click行为绑定函数
btn_right.addEventListener("click",right_fun,false);
btn_left.addEventListener("click",left_fun,false);
}
//右拐
function right_fun(){
move_lr(1,one);
//尝试把右拐按钮一同移动
move_lr(1,btn_right);
}
想要实现两个元素都右拐的效果,以及为什么会出现这种情况
#####move_lr中已经清除掉计时器了,所以只有最后一个有效,
该分别用2个计时器变量来记录自己的计时器,改下面就可以了
<style>
* {
padding: 0;
margin: 0;
}
#one {
width: 100px;
height: 100px;
background-color: #eba;
position: absolute;
left: 0;
top: 100px;
}
#line {
width: 1px;
height: 800px;
background-color: rgb(114, 90, 81);
position: absolute;
left: 800px;
top: 0;
}
button {
position: absolute;
}
</style>
<button id="btn_right">往右走</button>
<br>
<br>
<button id="btn_left">往左走</button>
<div id="one"></div>
<div id="line"></div>
<script>
var move
//左右移动函数,参数direction:1、-1为向左,1为向右;2.需要移动的元素
function move_lr(direction, obj,timername) {
clearInterval(window[timername]);////
//定时器持续移动obj
window[timername] = setInterval(function () {
var oldValue = obj.offsetLeft;
var newValue = oldValue + direction * 10;
if (newValue <= 0) {
newValue = 0;
}
else if (newValue >= 800) {
newValue = 800;
}
obj.style.left = newValue + "px";
if (newValue == 0 || newValue == 800) {
clearInterval(window[timername]);
}
}, 30);
}
//右拐
function right_fun() {
move_lr(1, btn_right,'timer1');
move_lr(1, one, 'timer2');
//尝试把右拐按钮一同移动
}
//左拐
function left_fun() {
move_lr(-1, one);
}
//监听click行为绑定函数
btn_right.addEventListener("click", right_fun, false);
btn_left.addEventListener("click", left_fun, false);
</script>
你可以写形参进去判断输出
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!