2013-05-31 18 views
1

我準備這樣的:當您將鼠標懸停在.container上時,它會更改兩者的顏色。但我只是想改變容器它在鼠標上

http://jsfiddle.net/hXpWh/2/

當你懸停.container它改變兩者的顏色。但我只是想改變鼠標所在的容器的位置。

這裏是js代碼:

moped = ""; 
$(".container").mouseenter(function() { 
    $(".content").css('background', function() { 
     moped = $(this).css('background'); 
     return "green"; 
    });}).mouseleave(function() { 
    $(".content").css('background', function() { 
     return moped; 
    }); 
}); 

HTML:

<div class="container"> 
    <div class="content"></div> 
    <div class="caption"> 
     <p>This is the caption of .container</p> 
    </div> 
</div> 
<div class="container2"> 
    <div class="content"></div> 
    <div class="caption"> 
     <p>This is the caption of .container2</p> 
    </div> 
</div> 

CSS:

.container { 
    position: absolute; 
    top: 0; 
    left: 0; 
    display: block; 
    z-index: 800; 
    width: 250px; 
    height: 250px; 
    padding: 0; 
    margin: 0; 
} 
.container2 { 
    position: absolute; 
    top: 0; 
    left: 255px; 
    display: block; 
    z-index: 800; 
    width: 250px; 
    height: 250px; 
    padding: 0; 
    margin: 0; 
} 
.content { 
    display: block; 
    background: red; 
    position: absolute; 
    z-index: 900; 
    top: 0; 
    left: 0; 
    width: 250px; 
    height: 250px; 
} 
.caption { 
    display: block; 
    background: none; 
    position: absolute; 
    z-index: 1000; 
    top: 0; 
    left: 0; 
    width: 250px; 
    height: 250px; 
} 
.caption p { 
    position: relative; 
    bottom: 10px; 
    left: 10px; 
} 
+4

當你完成其中兩個之後,它是否會讓你從你的小提琴中複製*一小段代碼? – BoltClock

回答

2

其他答案顯示jQuery代碼有什麼問題,但另一個解決方法是使用CSS。

給外部元件的共用類,那麼:

.cont { 
    background:red; 
} 
.cont:hover .content { 
    background: green; 
} 

DEMO:​​


但相對於jQuery代碼,您不僅需要找到嵌套0​​,但也沒有必要的變量。只需在mouseleave中將背景設置爲""即可。

$(".container").mouseenter(function() { 
    $(this).find(".content").css('background', "green"); 
}).mouseleave(function() { 
    $(this).find(".content").css('background', ""); 
}); 
+0

偉大的提示,謝謝! – user2437272

+0

@ user2437272:不客氣。 –

1

變化$(".content")$(this).find(".content").mouseenter功能,它只會改變一個你盤旋。您可以將其更改爲$(".content", this),但根據評論中的epascarello,它不是那麼高效。

+2

上下文選擇器性能較差,最好使用'$(this).find(「。content」)' – epascarello

+0

@epascarello哦,我沒有意識到。謝謝你,我會根據建議的用途更新答案。 –

+0

這就是我一直在尋找的。謝謝。那就是解決辦法:http://jsfiddle.net/hXpWh/5/ – user2437272

0

嗯,你可以任意移動CSS背景屬性或做到這一點:

moped = ""; 
$(".container").mouseenter(function() { 
    $(this).children(".content").css('background', function() { 
     moped = $(this).css('background-color'); 
     return "green"; 
    }); 
}).mouseleave(function() { 
    $(this).children(".content").css('background', function() { 
     return moped; 
    }); 
}); 

我的建議是用腳本做到這一點,並重構它,使用.hover()並分別命名mouseentermouseout功能。 祝你好運,伴侶。

相關問題