How to reset elements to their original state, after a chain of manipulations?

旧时模样 提交于 2019-12-19 08:52:04

问题


After a bunch of animating, adding classes and setting css styles. is there an easy way to reset an element to be back in its original server delivered state?


回答1:


jQuery sets its manipulations using the inline style attribute, so just set that to ''.

$('#someDiv').attr('style','');

This assumes there were no inline style attributes set on the element coming from the server. Better to use style sheets if so.

If the element must come from the server with style attributes set, then I suppose you could cache the value in a variable, and reset it when needed.

   // Cache original attributes
var originalAttributes = $('#someDiv').attr('style');


   // Reset from original
$('#someDiv').attr('style',originalAttributes);

EDIT:

If needed, you could send your elements from the server with custom attributes to remember the original class attribute, for example.

<div class="myClass" originalClass="myClass">...</div>

Then you can reference the original anytime you need.

You could even find all elements that have the originalClass attribute like this.

var $elementsWithOriginal = $('[originalClass]');

or find elements where the class attribute has been modified from the original.

var $modifiedFromOriginal = $('[originalClass]').filter(function() {
        return $(this).attr('class') != $(this).attr('originalClass');
    });


来源:https://stackoverflow.com/questions/2944874/how-to-reset-elements-to-their-original-state-after-a-chain-of-manipulations

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