繁体   English   中英

单击“类”时更改样式元素

[英]Changing a style element when a Class is clicked

因此,我有一个使用类名“ optin-box”的不带ID的元素,并且我有一个“ my-nav”类的导航项,当前具有margin-top:46px。 当我单击optin框时,我想从“ my-nav”类中删除页边空白

我最近得到的是:

 $(".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');
}); 

并尝试了变体,但我无法使其正常工作。 控制台日志输出,但导航确实没有移动。

您忘记关闭(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> 

这很简单。 请尝试以下操作:

$(".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', ''); }) 

 $(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切换mt

$(".my-nav").removeClass("mt");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM