【问题标题】:How to restore removed (.removeAttr()) attributes如何恢复已删除的 (.removeAttr()) 属性
【发布时间】:2013-06-18 03:32:22
【问题描述】:

所以这是我的问题,我使用 .removeAttr() 作为禁用内联样式的解决方法,现在有一个实例需要恢复我已删除的属性。还有可能吗?或者你能建议我使用什么替代解决方案。

removeAttr() 的触发器是来自浏览器的媒体查询。当浏览器调整大小时,dom中元素的位置也会改变。默认情况下,我的 html 有一个正在使用的内联样式。但是当它缩小时,它应该将元素移动到不同的位置,当它恢复到原始比例或在更宽的视图中时,它也应该恢复删除的属性。

var delay = (function(){
    var timer = 0;
    return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
    };
})();

jQuery(function() {

    var pause = 100; // will only process code within delay(function() { ... }) every 100ms.

    jQuery(window).resize(function() {

        delay(function() {

            var width = jQuery(window).width();

            if( width >= 958 && width <= 1400 ) {
                if(jQuery(".box1 #move_me").length == 0) {
                    // needs to restore the removed "style" attribute
                    jQuery("#move_me").appendTo(jQuery(".box1"));
                }
            } else if( width >= 768 && width <= 959 ) {

            } else if( width >= 480 && width <= 767 ) {
               jQuery("#move_me").insertAfter(".box2 .insert_below").removeAttr("style");
            } else if( width <= 479 ) {
               jQuery("#move_me").insertAfter(".box3 .insert_below").removeAttr("style");
            }

        }, pause );

    });

    jQuery(window).resize();

});

jsfiddle:http://jsfiddle.net/EFzy7/embedded/result/(调整大小以查看更改) - 如果您注意到,默认情况下如果您在更宽的屏幕中(例如,高于 960 像素或 1200 像素),“hello world”应该是红色的并且在arial 字体。当您调整大小时,它会移动到另一个 div/box。但是,当您将其调整回宽屏时,文本不是原来的样子(red-arial)。

有没有办法可以恢复已删除的属性?如果不是,您认为解决我的问题的方法是什么?

谢谢。

【问题讨论】:

  • $(".box2 .insert_below").data('oldstyle', $(this).prop('style')).removeAttr("style");,所以以后你可以用.data('oldstyle')来检索它。
  • 如果您删除了样式,则无法重新添加它,除非您在删除之前存储了它的值。
  • 恕我直言(如果您可以控制页面标记)解决方案是首先不使用内联样式
  • 我建议使用 CSS 类,例如 .toggleClass('className')
  • 是的,如果我可以只使用类而不是内联,这个过程可能会更容易。但不,我无法控制我试图操纵的标记。

标签: jquery responsive-design media-queries


【解决方案1】:

一种方法是在删除元素(或某些元素甚至文档)之前为其提供样式的数据值。然后您可以稍后通过该数据回忆起该样式。

像这样:

 jQuery("#move_me")
      .insertAfter(".box2 .insert_below")
      .data("reStyle", jQuery("#move_me").attr("style"))
      .removeAttr("style").removeAttr("style")

然后:

 jQuery("#move_me").attr("style", jQuery("#move_me").data("reStyle"))

Example

【讨论】:

  • 这行得通!我以后会更频繁地使用数据:) 谢谢你,@SpYk3HH
【解决方案2】:

最简单的方法是使用 CSS 类,但因为您无法操作标记。我只是将样式作为字符串存储在变量中。

所以,要获取样式使用var divStyle = $("#move_me).attr("style");,然后删除属性,并使用$("move_me").attr("style",divStyle); 恢复它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-23
    • 2021-09-21
    相关资源
    最近更新 更多