简体   繁体   中英

How can I undo the setting of element.style properties?

I have an element in my document that has a background color and image set through a regular CSS rule.

When a certain event happens, I want to animate that item, highlighting it (I'm using Scriptaculous, but this question applies to any framework that'll do the same).

new Effect.Highlight(elHighlight, { startcolor: '#ffff99', endcolor: '#ffffff', afterFinish: fnEndOfFadeOut });

The problem i'm facing is that after the animation is done, the element is left with the following style (according to FireBug):

element.style {
  background-color:transparent;
  background-image:none;
}

Which overrides the CSS rule, since it's set at the element level, so I'm losing the background that the item used to have...

What I'm trying to do is, in the callback function I'm running after the animation is done, set the style properties to a value that'll make them "go away".

var fnEndOfFadeOut = function() {
  elHighlight.style.backgroundColor = "xxxxx";
  elHighlight.style.backgroundImage = "xxxxx";
}

What I'm trying to figure out is what to put in "xxxx" (or how to do the same thing in a different way).
I tried 'auto', 'inherit', and '' (blank string), and neither worked (I didn't really expect them to work, but I'm clueless here).

I also tried elHighlight.style = ""; which, expectably, threw an exception.

What can I do to overcome this?
I know I can put a span inside the element that I'm highlighting and highlight that span instead, but I'm hoping I'll be able to avoid the extra useless markup.

Chances are you're not setting the style on the correct element. It's probably being set somewhere up the line in a parent node.

elHighlight.style.backgroundColor = "";
elHighlight.style.backgroundImage = "";

You can also remove all the default styling by calling:

elHighlight.style.cssText = "";

In any case, you'll still have to do this on the specific element that is setting these properties, which means you may need to do a recursion on parentNode until you find it.

Try
elHighlight.style.removeProperty('background-color') elHighlight.style.removeProperty('background-image')

have you tried elHightlight.style.background = "";?

I have a highlighter code on my site and this works

function highlight(id) {
var elements = getElementsByClass("softwareItem");
for (var ix in elements){
    elements[ix].style.background = ""; //This clears any previous highlight
}
document.getElementById(id).style.background = "#E7F3FA";
}

An HTML element can have multiple CSS classes. Put your highlight information inside a CSS class. Add this class to your element to highlight it. Remove the class to undo the effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM