Remove CSS “top” and “left” attributes with jQuery

后端 未结 13 1211
故里飘歌
故里飘歌 2020-12-02 07:07

Im building a draggable map that when the map is dragged the element is given a \'left\' and \'top\' attribute with values for each as so...

相关标签:
13条回答
  • 2020-12-02 07:55
     $("#map").css("top", "0"); 
     $("#map").css("left", "0"); 
    
    0 讨论(0)
  • 2020-12-02 07:58

    You can remove all of the contents in the style attribute by doing:

    $('.map').removeAttr('style');
    

    And you can remove specific styles by doing:

    $('.map').css('top', '');
    $('.map').css('left', '');
    
    0 讨论(0)
  • 2020-12-02 08:01
    $.fn.removeCss=function(toDelete){
    
        var props=$(this).attr('style').split(';');
    var tmp=-1;
    for( var p=0;p<props.length; p++){if(props[p].indexOf(toDelete)!==-1){tmp=p}};
    if(tmp!==-1){
    
       delete props[tmp];
    }
    
      return $(this).attr('style',props.join(';')+';');
    
    }
    

    Delete safely with this plugin!

    $('myDiv').removeCss('color');

    0 讨论(0)
  • 2020-12-02 08:06

    If you want to specifically remove top and left attributes and leave others, you can do this:

    $('.map').css('top', '').css('left', '');
    

    Or, a shorter equivalent:

    $('.map').css({
        'top': '',
        'left': ''
    });
    
    0 讨论(0)
  • 2020-12-02 08:08

    The default values for CSS top and left are auto, so setting them to that might be equivalent depending on what you're trying to do:

    $('.map').css('top', 'auto').css('left', 'auto');
    

    You also have the option of wholly removing the style attribute:

    $('.map').removeAttr('style');
    

    However, if you're using other jQuery UI components, those may require inline styles that you don't want to be removed, so proceed with caution there.

    0 讨论(0)
  • 2020-12-02 08:09

    In my opinion the cleanest way is to remove the property completely from the element's CSSStyleDeclaration, instead of just overwriting it with some kind of null/zero/default value:

    $(".foo").prop("style").removeProperty("top");
    $(".foo").prop("style").removeProperty("left");
    $(".foo").prop("style").removeProperty("background-color");
    
    0 讨论(0)
提交回复
热议问题