单击类时更改样式元素
因此,我有一个没有使用类名“optin-box”的ID的元素,并且我有一个导航项目,其中包含当前具有margin-top的“my-nav”类: 46px。当我点击选择启用箱,我想从“我的-导航”类别中删除的margin-top单击类时更改样式元素
最近我有是这样的:
$(".optin-box").on('click', (function(event) {
$(".my-nav").removeAttr("style");
console.log('firing');
});
或者这
$(".optin-box").click (function() {
$(".my-nav").css('margin-top', '0 !important');
console.log('firing');
});
并试过各种变化,但我无法得到它的工作。控制台日志输出,但导航完全移动。
这很简单。请尝试以下操作:
$(".optin-box").on('click', (function(event) {
$(".my-nav").css("margin-top", ""); //Thi will remove margin-top from your style tag
}));
您必须将值设置为您要修改的样式。
$('my-nav').css ('margin-top': 0);
试试这个,它会将边距重置为0px。
$('.my-nav').css('margin-top', '');
实施例:
<p id="change" style="margin-top:20px"> Let me check </p>
<input type="button" value="ChangeMargin" id="btn">
$('#btn').click(function()
{ // alert('btn')
$('#change').css('margin-top', ''); })
请解释此代码为何有所帮助。 – Raidri
虽然这段代码片段是受欢迎的,并且可能会提供一些帮助,但它会[如果它包含解释](/ meta.stackexchange.com/q/114762)* how *和* why *会大大改进,这将解决问题。请记住,你正在为将来的读者回答这个问题,而不仅仅是现在问的人!请编辑您的答案以添加解释,并指出适用的限制和假设。 –
更新,好的谢谢,我会记住 –
你忘了关(function(){})
,加入)
到的函数的末尾。
$(".optin-box").on('click', (function(event) {
$(".my-nav").removeAttr("style");
console.log('firing');
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-nav" style="margin-top:50px;">my-nav</div>
<button type="button" class="optin-box">optin-box</button>
$(document).ready(function(){
$(".abc").click(function(){
$(".my-nav").css("margin-top", "0px");
});
});
div{
border:1px solid;
margin-top : 50px;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<body>
<div class="my-nav">
<h3>This is a heading in a div element</h3>
<p>This is some text in a div element.</p>
</div>
<p class="abc">Click here</p>
</body>
</html>
更好是有一个类定义了余量
.mt {
margin-top: 40px;
}
使用addClass/removeClass以切换公吨
$(".my-nav").removeClass("mt");
这将有助于在此处查看您的实际HTML和CSS。如何将“margin-top”应用于元素?通过“样式”或CSS类? –
您可以创建另一个类并使用'.removeClass('existing class_name')'然后'addClass('new_class')' –
它是否通过css或style应用并不重要。检查[小提琴](https://jsfiddle.net/prwrp3xk/),它的工作正常。恐怕您访问错误的元素 – MUT