jQuery - Selecting a child div background image and amending it

蹲街弑〆低调 提交于 2019-12-08 01:30:10

问题


Im looking for a way to change the background image of a div using jQuery BUT only amending it, not totally changing it.

Let me explain.

Im using http://jqueryui.com/demos/sortable/#portlets to show some div's that open and close. Now when you click the portlet header it opens and closes the content below.

Inside the portlet header i have a child div which shows an arrow (either up or down) depending on the current state of the content. I need a way of changing the background image on this child div by adding on "-visible" onto the end of the url for the background image.

I wouldnt even know where to start with doing this, but i have added some code below for you to look at.

http://jsfiddle.net/45jZU/

From the fiddle there, i need to alter the background image of the portlet-arrow div inside portlet header. I can not simply change the background image all together, but i have simplified it down to post on here.

I hope this isnt too narrow to not be of use to anyone else on stackoverflow.

Thanks


回答1:


Maybe I'm missing something here, but can't you use the .css attribute modifier for the selected jQuery object? Something like:

var current_background = $("#my-div").css("background-image");
$("#my-div").css("background-image", current_background + "-visible");

If you're looking to modify the class names themselves, you can try mess around with the .toggleClass(), .hasClass(), .addClass() and .removeClass() methods in jQuery.

I hope this helps, but let me know if I've missed the mark here completely!




回答2:


I would personnaly go for using css classes to change the background image. If you decide to change the image afterwards, you won't have to alter your javascript. It is a better solution to use javascript to code the behavior of the widget, not the visual aspect.

So you have the following css:

.portlet-header {
    background-image: url(<an image>);
}

.portlet-header.collapsed {
    background-image: url(<an other one>);
}

Add this line to your javascript to toggle the collapsed class:

$(".portlet-header").click(function() {
    ...
    $(this).parent().toggleClass('collapsed');
});

If you widgets starts collapsed, initially add the class.

DEMO



来源:https://stackoverflow.com/questions/8923849/jquery-selecting-a-child-div-background-image-and-amending-it

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