gpt4 book ai didi

jquery - 在动画中动态选择CSS属性

转载 作者:行者123 更新时间:2023-12-01 00:21:04 25 4
gpt4 key购买 nike

这似乎是一件简单的事情,但我并没有取得多大成功。我只是使用 animate() 实现一个简单的动画,将 div 向左或向上移动,但我希望能够动态设置“顶部”和“左侧”CSS 属性。我想使用相同的函数,而不是必须有两个,一个用于“左”,一个用于“上”。

这里有一些代码给出了这个想法。


function test($element){
$element.click(function(){
var cssProperty;
var direction = "left";
var moveTo = "100px";

if (direction === "top") {
cssProperty = "top";
} else {
cssProperty = "left";
}

/*Using variable as CSS property - This doesn't work */
$(this).animate({
cssProperty: moveTo
}, 1000);

/*Using variable as the CSS Values - This does */
$(this).animate({
left: moveTo
}, 1000);
});
}

变量适用于 css 值端,但不适用于 css 选择器端。大家有什么建议吗?

谢谢

最佳答案

请参阅:http://www.jibbering.com/faq/faq_notes/square_brackets.html

function test($element){
$element.click(function(){
var cssProperty;
var direction = "left";
var moveTo = "100px";
var animationProperties = {};

if (direction === "top") {
cssProperty = "top";
} else {
cssProperty = "left";
}

animationProperties[cssProperty] = moveTo;

// This does work.
$(this).animate(animationProperties, 1000);

// Or else, using computed properties introduced in ES6.
$(this).animate({
[cssProperty]: moveTo
}, 1000);
});
}

Browser support对于 computed properties .

关于jquery - 在动画中动态选择CSS属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2697817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com