2012-10-15 104 views
1

我已經環顧了這個論壇很多,只能找到與我的問題相反,換句話說,我期待找到如何改變父div的背景,當孩子div懸停,當父母徘徊時,我只能找到如何更改子div。在兒童懸停上更改父css

我有一個內1個父DIV提交按鈕:

<div class="ugd_ele_normal_base"> 
    <input name="ugd_1" type="submit" class="ugd_ele_normal"/> 
</div><!--end ugd_ele_normal_base--> 

我想要的是,當提交按鈕上空盤旋了,父CSS改變背景。

我已經嘗試了一些東西,但似乎沒有任何工作。

感謝您的幫助

+1

http://reference.sitepoint.com/javascript/Node/parentNode – TheZ

+1

隨着CSS4你就可以做'.ugd_ele_normal_base! > .ugd_ele_normal:hover {background:red; '',但這對你現在沒有什麼幫助。所以我甚至不會提起它。 – jessegavin

+1

CSS4 wtf?不知道我們是否會因爲實施的時間而活着:3 – yoshi

回答

5

我會用這個jQuery & CSS:

CSS

.black { 
    background-color: #000000; 
} 

的jQuery

$(function() { 
    $('.ugd_ele_normal').hover(function(){ 
     $(this).parent().addClass("black"); 
    }, 
    function(){ 
     $(this).parent().removeClass("black"); 
    }); 
}); 
+0

+1將樣式狀態存儲在CSS而不是JS中總是一個好主意。分離關注點,可維護性等 –

+2

偉大的姓氏馬特:) – Stone

0

嘗試:

$('input[name="ugd_1"]').hover(function() { 
    $(this).parent().css('background-color', 'COLOR'); 
}); 

希望它能幫助。

4
$('input.ugd_ele_normal').on({ 
    mouseenter: function() { 
     $(this).parent().css('background', 'url(/folder/image1.jpg)'); 
    }, 
    mouseleave: function() { 
     $(this).parent().css('background', 'url(/folder/image2.jpg)'); 
    } 
}); 

或短(ER)版本:

$('input.ugd_ele_normal').on('mouseenter mouseleave', function(e) { 
    $(this).parent() 
      .css('background-color', e.type=='mouseenter'?'url(/folder/image1.jpg)':'url(/folder/image2.jpg)'); 
}); 

和檢索舊形象:

var bgImg = $('input.ugd_ele_normal').css('background-image'), 
    hvImg = 'url(/folder/image2.jpg)'; 

$('input.ugd_ele_normal').on('mouseenter mouseleave', function(e) { 
    $(this).parent() 
      .css('background-image', e.type=='mouseenter'?hvImg:bgImg); 
}); 

或使用類:

.hoverClass {background: url(/folder/image2.jpg);} 

-

$('input.ugd_ele_normal').on('mouseenter mouseleave', function() { 
    $(this).toggleClass('hoverClass'); 
}); 
+0

Thankyou非常感謝您的回答,它工作得很好,唯一的一點是,我實際上是在處理圖像,所以如何如果我在2張圖片之間切換,我會這麼做嗎?而不是顏色 – Arken

+0

+ 1在短版本中巧妙地使用e.type :-) – Nelson

1

你可以這樣做。

$("#ugd_1").hover(function(){ 
    $(this).parent().css("background","red"); 
}, 
function(){ 
     $(this).parent().css("background","none"); 
}); 

現場演示:

http://jsfiddle.net/Z4QDC/2/

1

我會定義一些jQuery來做到這一點,並使用自定義類。

//when the document is loaded, execute the following code 
$(document).read(function(){ 

//on this elements hover, ... 
$('.ugd_ele_normal').hover(function(){ 
    //we add the class black to the parent on hover 
    $(this).parent().addClass("black"); 
}, 
function(){ 
    //and remove it on exit hover. 
    $(this).parent().removeClass("black"); 
}); 
}); 

可以在行動中可以看出這裏: http://jsfiddle.net/xBuyC/

相關問題