Problem changing background image using Javascript
I'm trying to change the background image of a link when it is clicked via Javascript. I five tabs and when the user clicks on a tab, I want the background image of that tab to change to a plain white image. Where as the other four tabs should be changed to a grey image.
So my CSS is as follows:
.listingindex li a {
background:url(../images/tabe-nomal.jpg) left top no-repeat;
color:#333333;
display: inline-block;
text-decoration:none;
width:229px;
padding:14px 0px 14px 10px;
}
.listingindex li a:hover {
background:url(../images/tabe-over.jpg) left top no-repeat;
}
and my code looks like this:
<div class="listingindex">
<?php
$catId = get_cat_id('featured');
$childOf = 'child_of='.$catId;
$subCats = get_categories($childOf);
// Slice array so only 5 categories can be displayed.
$subCats = array_slice($subCats, 0, 5);
foreach ($subCats as $value) {
$subCatsStr .= $value->cat_ID.'|';开发者_Go百科
}
foreach ($subCats as $subCat) {
?>
<ul>
<li><a id="tab_<?=$subCat->cat_ID?>" href="javascript:toggle(<?=$subCat->cat_ID?>,'<?=$subCatsStr?>')"><?=$subCat->name?></a></li>
</ul>
<ul id="thumbnails_<?=$subCat->cat_ID?>" class="listingarea">
<?php $query = new WP_Query('category_name='.$subCat->name.'&posts_per_page=9');
while( $query->have_posts() ) : $query->the_post();?>
<li>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<?
$id = $post->ID;
$filename = $_SERVER["DOCUMENT_ROOT"].'/xxxxxxx/xxxxxx/xxxxx/xxxxxx/images/thumbnails/image_'.$id.'.jpg';
if (file_exists($filename)) {
?><img src="<?php echo $templateDir; ?>/images/thumbnails/image_<?=$id;?>.jpg" alt="Image_<?=$id;?>" /><?
}else{
?><img src="<?php echo $templateDir; ?>/images/thumbnails/no_image.jpg" alt="No Image" /><?
}?>
</a>
</li>
<?php endwhile; ?>
</ul>
<?}?>
</div>
Lastly my JS looks like this:
function toggle(catID, subCatsStr) {
document.getElementById('thumbnails_'+catID).style.display = "block";
document.getElementById('tab_'+catID).style.backgroundImage = "url(/images/tabe-over.jpg)";
subCatsArr = subCatsStr.split('|');
for (i = 0; i <= subCatsArr.length - 2; i++){
if (subCatsArr[i] != catID){
document.getElementById('thumbnails_'+subCatsArr[i]).style.display = "none";
document.getElementById('tab_'+catID).style.backgroundImage = "url(images/tabe-nomal.jpg) left top no-repeat";
}
}
}
At the moment, this code simply removes the grey image (tabe-nomal.jpg) when a tab is clicked.
Any help appreciated.
Regards...
Looks like your backgroundImage urls might not be correct -- try using the same path (../images/..) as in your initial css rule
To solve the problem in the end I had to specify the full path name:
document.getElementById('tab_'+catID).style.backgroundImage = "url(http://www.xxxxxx.ie/xxxxxxx/wp-content/themes/xxxxxxx/images/tabe-over.jpg)";
Not sure why, but this solved the problem. Its a Wordpress theme so maybe this had something to do with it.
精彩评论