开发者

Is there a way to cut and paste or clone CSS from one element to another using JQuery?

I have a situation where I'm wrapping an image with a span and I want to remove all the CSS from the image and apply it to the span. Is there a way to do this with JQuery?

JQuery:

$(img).wrap('<span />');

Style Sheet:

img { border: 5px solid red; padding: 10px; … nee开发者_JAVA技巧ds to allow for anything }

I would like to do this with out editing the HTML or CSS. I need a way to truly remove the CSS from one element and place it on another.


There's also toggleClass(), which simply applies the class if it is not already on the element, and removes it if it is.

$("#imageIDHere,#otherThing").toggleClass("theClass");

I have a feeling, looking at your question, that you're planning for some kind of dynamic CSS structure. You can absolutely change classes, CSS selectors and their properties dynamically, using things like this jQuery plugin. However, doing this without any class structure at all or overarching system is most likely setting you up for a lot of headaches down the line.


Can't you just apply your CSS class to the span (and remove from the image)?

See .addClass and .removeClass.


You can use the removeClass and removeAttr to remove the style depening on your requirement.

Examples:

$('selector').removeClass('some_class'); // this removes some_class
$('selector').removeClass(); // this removes all classes
$('selector').removeAttr('class'); // this removes inline classes
$('selector').removeAttr('style'); // this removes inline styling
$('selector').removeAttr('id'); // this removes id styling


I would probably do something like this:

/*CSS*/
.style{border:solid 1px red;}

/*JQuery*/

$("#imageIDHere").removeClass("style");
$("#spanIDHere").addClass("style");

/*or*/

$("#imageIDHere").removeClass("style").parent().addClass("style"); //assuming the span is the parent of the image
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜