【问题标题】:How do i use a simple string variable with jquery?如何在 jquery 中使用简单的字符串变量?
【发布时间】:2017-04-18 15:32:33
【问题描述】:

我有这个代码:

$(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", "transform":"scale(0.8)", "marginTop":"-50px", "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,这是它不起作用的原因吗?

【问题讨论】:

  • 原因是jQuery的.css()方法不接受string如果你想设置多个属性,而是需要一个object包含匹配CSS的键值对你想改变的规则。

标签: javascript jquery css string var


【解决方案1】:

原因是如果你想设置多个属性,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");

【讨论】:

    【解决方案2】:

    您将对象表示为字符串。你应该这样做

    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"');

    至于您的下一行,您将 {} 混淆为字符串。如果您使用上面的变量定义,并删除 { ++ } 那么它应该可以工作。

    【讨论】:

    • 谢谢,我用的是顶级版本,效果很好。如果我想在 jquery 代码中使用两个不同的变量,我该怎么办?我正在尝试 $("div.modal-content3").css(test + test2);但它似乎不起作用。
    • @Peter 你能分享testtest2 的值以便我给出正确的代码吗?
    • var test = {"zIndex":"3", "transform":"scale(0.8)", "marginTop":"-50px"}; var test2 = {"animationName":"animleft", "animationDuration":"0.7s"}; $("div.modal-content3").css(test + test2);我只是想在 div modal-content3 中插入​​一堆 CSS 文本,但如果可能的话,css 值应该来自两个不同的变量,test 和 test2
    • 你有两个对象,你会想做test.assign(test2)。这会将test2 合并到test,更改测试并返回它的新值(您应该传递给jQuery 的值) - 请参阅stackoverflow.com/questions/171251/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 2016-06-28
    相关资源
    最近更新 更多