jquery onclick add margin-left

这一生的挚爱 提交于 2020-01-25 03:36:05

问题


I'm trying something pretty simple in JS but I can't make it work...

I would like when clicking on a div to add a negative margin-left to another div, but I want it to happened everytime I click on the div, not only one time as it does now. Eveytime I click on my #next_nav, I would like the #nav to move from 10px negative. here it only works one time. here is my js :

$(function() {
  $('#next_nav').click(function () {
     $( "#nav" ).css('margin-left','-10px');
  });
});

and my HTML :

<div id="next_nav"></div>
<div id="nav"></div>

here is my JSfiddle : http://jsfiddle.net/Beyzd/

can anybody helps me with this ? thanks a lot,


回答1:


add an = in front of your value:

$(function() {
    $('#next_nav').click(function() {
       $('#nav').css('margin-left', '-=10px');
    });
});

Working Fiddle

EDIT

If you want to animate it, use animate() method. Here is a fiddle for you.




回答2:


You can try this

var pixels=0;
$(function() {
    $('#next_nav').click(function () {
       pixels=pixels-10;      
       $( "#nav" ).css('margin-left',pixels);
    });
});

Working fiddle is available here.




回答3:


Check on jsFiddle

   $(document).ready(function (){
       $("#next_nav").on("click", function() {
          var $left = $("#nav").css('margin-left');
          var $newval = (parseInt($left) - 10) + "px";
          $("#nav").css ({
            'margin-left' : $newval
          });
       });
   });



回答4:


Fixed it for you: Updated version

edit the .css('margin-left','-10px'); to .css({'margin-left' : '-10px'});




回答5:


Try this:

$(function() {
$('#next_nav').click(function () {
  marginleft=parseInt($( "#nav" ).css('margin-left').replace('px',''));
  $( "#nav" ).css('margin-left',marginleft-10+'px');
});
});

Working Fiddle




回答6:


just change this $( "#nav" ).css('margin-left','-=10px');




回答7:


$(function() {
  var count=0;
  $('#next_nav').click(function () {
  count-=10;

$( "#nav" ).css('margin-left',count);
});
});

And include jQuery



来源:https://stackoverflow.com/questions/22146904/jquery-onclick-add-margin-left

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!