Apply jQuery “highlight” theme styles using javascript?
-
16-06-2021 - |
Pregunta
I'm using jQuery UI Themes with one of my web applications.
If I want to apply button styling, I add the following jquery code:
$(".button").button();
Where .button
is a class on the button I wish to style with jquery themes.
How can I do a similar thing to apply theme styles to an element which I want to style as a "highlight"?
I tried .highlight();
, but this hasn't worked.
Note: I'm aware that I can manually add the CSS classes to my elements, but I wish to apply this with jQuery as this would save me adding the span
element which displays the icon.
Therefore I want to be able to have the following HTML code:
<div class="highlight">
<strong>Warning!</strong> Lorem Ipsum
</div>
Which is then converted, using jQuery, into:
<div class="highlight ui-state-highlight ui-corner-all" style="margin-bottom:20px">
<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>
<strong>Warning!</strong> Lorem Ipsum</p>
</div>
Or, have I misunderstood what the use of the "Highlight" example is on the Theme roller page? I've assumed this is a warning box, considering its next to an error example.
Solución
$.fn.highlight = function() {
return this.each(function() {
var elem = $(this), p = $("<p>", {
html: '<span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>' +
elem.html()
});
elem.empty().addClass("ui-state-highlight ui-corner-all").append(p);
});
};
$(".highlight").highlight();
Otros consejos
I feel like I may be missing the point here, but you've said you want to do this "with jQuery", so:
$(".highlight").each(function() {
var elm, p;
elm = $(this);
// Create the new paragraph and span
p = $('<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span></p>');
// Add the classes to the element
elm.addClass("ui-state-highlight ui-corner-all");
// Move the element's children into the paragraph
p.append(elm.contents());
// Append the paragraph
elm.append(p);
});
Plugin keeps existing ID and classes
(function($){
$.fn.highlight=function(){
return this.each(function(){
var text=$(this).text();
var id=this.id;
var thisClass=$(this).attr('class');
var $el=$('<div class="highlight ui-state-highlight ui-corner-all" style="margin-bottom:20px">\
<p><span class="ui-icon ui-icon-info" style="float: left; margin-right: .3em;"></span>\
<strong>'+text+'</strong> Lorem Ipsum</p>\
</div>').attr(id, id).addClass( thisClass);
$(this).replaceWith($el);
});
};
})(jQuery);
$(anyElement).highlight();