gpt4 book ai didi

javascript - 用普通 CSS 覆盖 jQuery 中应用的 CSS(没有 !important)

转载 作者:行者123 更新时间:2023-11-30 09:27:36 26 4
gpt4 key购买 nike

所以我遇到了以下问题:

我用这个 CSS 得到了一个元素($(this) 是克隆的对象):

clone.css({
'width': $(this).width() + 'px',
'height': $(this).height() + 'px',
'top': $(this).offset().top - $(window).scrollTop() + 'px',
'left': $(this).offset().left + 'px',
'position': 'fixed'
});

点击我添加以下类:

.dupe{
top:0;
left:0;
width:100%;
height:300px;
border-radius:0;
box-shadow:none;
transition:all .3s ease-in-out;
}

但这行不通,因为 jQuery 会覆盖它。我不想使用 !important

那么有没有一种方法可以在不使用 !important 的情况下告诉 CSS “现在你很重要,现在你不重要”?

最佳答案

使用 jQuery.css 将样式设置为元素的内联样式。您将需要使用 !important 从样式表中覆盖它。

处理此问题的一种方法是为所有样式使用类名并使用类来切换样式。

如果这不是一个选项,您可以在单击后使用 jQuery.css 将属性重置为其初始值(通过将它们设置为 '')或将它们设置为所需的值。

将它们设置为 '' 的实例:

var clone = $(".target").clone();
clone.css({
'width': '80px',
'height': '20px',
'top': '40px',
'left': '50%',
'position': 'fixed'
});
clone.appendTo(document.body);
console.log("Added styling to clone");
setTimeout(function() {
console.log("Removed styling from clone");
clone.addClass("dupe").css({
'width': '',
'height': '',
'top': '',
'left': '',
'position': ''
});
}, 800);
.target {
border: 1px solid #ddd;
}
.dupe {
color: blue;
}
<div class="target">
Hi there
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

如果这也是一个选项,您也可以使用 jQuery.removeAttr 完全删除样式属性。这将有效地删除内联样式,从而让您的其他样式生效。但它也会删除元素具有的任何其他内联样式。

完全删除 style 属性的实例:

var clone = $(".target").clone();
clone.css({
'width': '80px',
'height': '20px',
'top': '40px',
'left': '50%',
'position': 'fixed'
});
clone.appendTo(document.body);
console.log("Added styling to clone");
setTimeout(function() {
console.log("Removed styling from clone");
clone.addClass("dupe").removeAttr("style");
}, 800);
.target {
border: 1px solid #ddd;
}
.dupe {
color: blue;
}
<div class="target">
Hi there
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

关于javascript - 用普通 CSS 覆盖 jQuery 中应用的 CSS(没有 !important),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48379938/

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