【问题标题】:JQuery Set width !important after variable [duplicate]JQuery设置宽度!变量后重要[重复]
【发布时间】:2013-06-30 16:30:26
【问题描述】:
$(".mydiv").css('width', $(".image").width());

这段代码有效,但我想让这个宽度很重要,正确的方法是什么?

我试过了,但是没用

$(".mydiv").css('width', $(".image").width()+'!important');

(!重要)

【问题讨论】:

  • 如果行得通,你为什么要做!important

标签: jquery variables width set


【解决方案1】:

问题是由于 jQuery 不理解 !important 属性导致的,因此无法应用规则。

您也许可以解决这个问题,并通过 addClass() 引用它来应用规则:

.importantRule { width: 100px !important; }
 $('#mydiv').addClass('importantRule');

或者使用 attr():

$('#mydiv').attr('style', 'width: 100px !important');

请参考以下问题:- How to apply !important using .css()?

【讨论】:

  • 问题是;我不使用 100 px,它是一个变量
【解决方案2】:

试试这个

        var previousStyle = $(".mydiv").attr('style')
        $(".mydiv").attr('style', 'width:' + $(".image").width() + '!important; ' + previousStyle + '');

重要属性 $(文档).ready(函数 () { var previousStyle = $(".mydiv").attr('style') $(".mydiv").attr('style', 'width:' + $(".image").width() + '!important; ' + previousStyle + ''); }) 查看

<html>
<head>
    <title>Important Attribute</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () { 
            var previousStyle = $(".mydiv").attr('style')
            $(".mydiv").attr('style', 'width:' + $(".image").width() + '!important; ' + previousStyle + '');
        })
    </script>
</head>
<body>
    <div class="mydiv" style="border: 1px solid black; width: 200px">check</div>
    <div class="image" style="width: 280px"></div>
</body>
</html>

如果您检查并查看 mydiv 属性,您可以看到宽度和重要标签,如 jquery 语句所述

【讨论】:

  • 这在某种意义上是可行的,但如果元素中包含任何其他信息,它将全部被替换
  • 这不起作用:/
  • 我刚刚测试过哪个可以工作,现在也不会覆盖以前的样式。希望这会有所帮助。
  • 你能告诉我什么不工作吗?
  • @Raghurocks 我用了你的代码,它不起作用
【解决方案3】:

你必须改变 $(".image").width()+'!important' 与

$('.image').css('width');

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-01
    • 2019-11-02
    • 1970-01-01
    相关资源
    最近更新 更多