jquery on click add css value in percentage [closed]

混江龙づ霸主 提交于 2021-02-08 12:04:48

问题


I'd like to add 100% incrementally to margin left on click.

So say my current margin value is 100% Then On click = 200% On second click = 300% and so on...

How do I do this? I searched all over, can't find a solution. It's easy to add 100 pixels but i need percentage value.

Thanks!


回答1:


For browser consistency, I would suggest you to use this kind of snippet:

EDITED FOLLOWING COMMENT

DEMO

$('.slide-back').data('marginLeft',10).on('click',function(){
    var $inner = $('.inner'), curMarg = $(this).data('marginLeft') + 10;
    $inner.css({marginLeft:curMarg+'%'});
    $(this).data('marginLeft',curMarg);
});



回答2:


I don't understand why are you doing such thing. (margin in percentage).
But here it is: Check Out LIVE DEMO

jQuery

$('.mydiv').click(function()
{
    var currentMargin = parseInt($(this).css('margin-left'));
    $(this).css('margin-left',currentMargin+100+'%');
});

HTML

<div class='mydiv'></div>

CSS

.mydiv
{
    background-color:red;
    width:100px;
    height:100px;
    position:absolute;
    margin-left:100%;
}



回答3:


I don't really understand the question too but, if you try to get the margin doubled, in PX , %, or whatever, you can do it that way (based on roasted fiddle) :

$('b').click(function(){
  var curMargStr = $(this).css('marginLeft');
  var curMarg = curMargStr.replace('px','') * 2;
  $(this).css('marginLeft', curMarg);
});

You can't get the value in percent, as the browser has to translate in px to render it. Note the value can change depending on the browser you're using.



来源:https://stackoverflow.com/questions/16870861/jquery-on-click-add-css-value-in-percentage

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