jQuery cssText 不使用变量

jQuery cssText not working with variables

本文关键字:变量 cssText jQuery      更新时间:2023-09-26

>我有一个简单的最小示例,其中包含两个框的html代码:

<div class="box current" style="background: red"></div>
<div class="box" style="background: blue"></div>

还有一个 css,它使框默认不可见:

.box{
  position: absolute;
  width: 50px;
  height: 50px;
  opacity: 0;
}

而且,一个简单的jquery代码,它应该使带有类"current"的div被某个变量ammount可见

var opacity = 0.7;
//Yes, the code has to use a variable. 
//NOT a static value;
$(".current").css("cssText", "opacity: " + opacity + " !important;");

然而,由于未知原因,这段代码似乎根本不起作用。将当前框的 css 设置为静态重要使其工作得很好......对于不透明度的静态值。代码笔链接

关于该主题的任何帮助都将是惊人的

使用这个 ::

$(".current").css("opacity" ,""+ opacity );

而不是

$(".current").css("cssText", "opacity: " + opacity + " !important;");

希望这对:)有所帮助

将你的css更改为这个

.box{
  position: absolute;
  width: 50px;
  height: 50px;
  display:none;
}

和你的 JS 像这样

$(document).ready(function(){
  $(".current").fadeIn(3000);
});

这将为您提供漂亮的淡出动画。我编辑了你的代码笔链接。试试这个。如果这不是你想要的,告诉我。

试试这个

var opacity = 0.7;
//Yes, the code has to use a variable. 
//NOT a static value;
$(".current").css("opacity"+","+ opacity + " !important;");

cssText 设置或获取规则的内容,因此您需要将其附加到现有规则中,因为它会覆盖它。

var opacity = 0.7;
$(".current").css("cssText", $('.current').css('cssText') + "opacity: "+ opacity +" !important;");

试试这个。它有效。

$(function(){
   var opacity = 0.7;
   $(".current").css({"opacity": opacity });
});