我有这段代码:
$(function(){
$( "div.modal-content3" ).on( "swipeleft", swipeleftHandler );
function swipeleftHandler( event ){
if ($('.modal-content').css('display') == 'block' && $('.modal-content2').css('display') == 'block') {
$("div.modal-content3").css({"zIndex":"3", "transform":"scale(0.8)", "marginTop":"-50px", "animationName":"animleft", "animationDuration":"0.7s"});
$("div.modal-content2").css({"zIndex":"4", "transform":"scale(0.9)", "marginTop":"-25px", "animationName":"none", "animationDuration":"0"});
$("div.modal-content").css({"zIndex":"5", "transform":"scale(1)", "marginTop":"0px"});
}
我如何将css部分放在代码中:
" zIndex":" 3","转换":"比例(0.8)"," marginTop&#34 ;:" -50px&#34 ;, " animationName":" animleft"," animationDuration":" 0.7s"
并将其放在一个变量中,以便以后插入到jquery代码中?
我尝试过这样的事情,但没有成功:
var test = '"zIndex":"3", "transform":"scale(0.8)", "marginTop":"-50px",
"animationName":"animleft", "animationDuration":"0.7s"';
$("div.modal-content3").css({ + test + });
我混合了javascript和jquery,这是它不起作用的原因吗?
答案 0 :(得分:3)
您将对象表示为字符串。你应该做
var test = {"zIndex":"3", "transform":"scale(0.8)", "marginTop":"-50px",
"animationName":"animleft", "animationDuration":"0.7s"};
或者你可以解析你拥有的JSON
var test = JSON.parse('"zIndex":"3", "transform":"scale(0.8)", "marginTop":"-50px",
"animationName":"animleft", "animationDuration":"0.7s"');
至于你的下一行,你会混淆{
和}
字符串。如果您使用上面的变量定义,并删除{ +
和+ }
,那么它应该有效。
答案 1 :(得分:0)
原因是,如果要设置多个属性,jQuery的.css()
方法不接受string
,而是需要object
包含键值对匹配您想要更改的CSS规则。
var test = { "zIndex":"3", "transform":"scale(0.8)", "marginTop":"-50px", "animationName":"animleft", "animationDuration":"0.7s" };
$("div.modal-content3").css(test);
即使这样有效,但感觉就像你在这里过于复杂。
为什么不简单地创建以下CSS类:
.my-class {
z-index: 3;
transform: scale(0.8);
margin-top: -50px;
animation-name: animleft;
animation-duration: 0.7s
}
这将简化您的jQuery
$("div.modal-content3").addClass("my-class");