我在玩 jquery 时遇到了一个问题。
我想在它的容器悬停时为一个盒子设置动画,这样每次容器悬停时,盒子(初始状态 1)应该重置到一个位置(比如状态 2)然后动画到所需位置(比如状态 3) .
HTML
<div id="box-container">
<div id="box"></div>
</div>
CSS
#box-container {
padding : 10px;
border : 1px solid #f00;
}
#box {
display: inline-block;
background : #fff;
padding:50px;
border: 1px solid #ddd;
transform : translateX(150px);
}
JS
$("#box-container").hover(function(){
console.log("hover in");
$("#box").css({
transform : 'translateX(0px)',
transition : 'initial'
}).css({
transform:'translateX(100px)',
transition : 'transform 0.5s linear'
});
},function(){
console.log("hover out");
});
但是这个方法行不通。框直接从 state 1 -> state 3
进入并卡住。我发现 css()
不能像 jquery 中的 animate()
一样排队
工作模型 1 => JSfiddle
所以我试图打破链条并尝试通过这样做来增加一些延迟
$("#box").css({
transform : 'translateX(0px)',
transition : 'initial'
});
setTimeout(function(){console.log("delay")}, 1000);
var x = 4;
console.log("delay");
$("#box").css({
transform:'translateX(100px)',
transition : 'transform 0.5s linear'
});
但这行不通,所以我尝试了 delay()
,这是第一次运行良好。但是第二次盒子卡在了左边
工作模型 2 => JSfiddle
最后我尝试在第一次更改(state 2
)之后记录框的(transform、padding、transition 等)的 css 值
console.log($("#box").css('transform'));
不知何故,它按照我希望的方式工作
工作模型 3 => JSfiddle correct
- So i want to know why reading css value gives the desired output
- what is the good way to achieve this output
state 1 (hover)-> state 2 -> state 3 (hover)-> state 2 -> state 3
在 chrome(最新版本)上检查时,所有链接都工作正常。
最佳答案
除非您刚开始使用变换属性,否则您可以只使用 jQuery 动画来移动您的元素。
修改后的 CSS:
#box-container {
padding : 10px;
border : 1px solid #f00;
position: relative;
}
#box {
display: inline-block;
background : #fff;
padding:50px;
border: 1px solid #ddd;
position: relative;
left: 150px;
}
修改后的 JavaScript
$("#box-container").on('mouseover',function(){
$('#box').animate({
left: "0"
}, 10, function(){
}).animate({
left: "100"
}, 300, function(){
});
}).on('mouseout',function(){
$('#box').animate({
left: "150"
}, 0, function(){
});
});
关于javascript - 忽略使用 css 方法的 Jquery 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536710/