所以我看到所有组件都受到了mouseenter()的影响后添加了.each(),但因为这是一个图库......我只想让一个组件受到影响..
$(document).ready(function(){
$(".component").each(function(){
$(this).mouseenter(function(){
$(".primary").css({"margin-right":"0", "transition":"1s"});
$(".secondary").css({"margin-left":"0", "transition":"1s"});
});
$(this).mouseleave(function(){
$(".primary").css({"margin-right":"30px", "transition":"1s"});
$(".secondary").css({"margin-left":"30px", "transition":"1s"});
});
});
});
答案 0 :(得分:2)
使用.children()
或.find()
像这样:
$(document).ready(function() {
$(".component").each(function() {
$(this).mouseenter(function() {
$(this).children(".primary").css({
"margin-right": "0",
"transition": "1s"
});
$(this).children(".secondary").css({
"margin-left": "0",
"transition": "1s"
});
});
$(this).mouseleave(function() {
$(this).children(".primary").css({
"margin-right": "30px",
"transition": "1s"
});
$(this).children(".secondary").css({
"margin-left": "30px",
"transition": "1s"
});
});
});
});
* {
box-sizing: border-box;
}
.flex {
display: flex;
justify-content: center;
align-items: center;
}
.row {
flex-direction: row;
}
.column {
flex-direction: column;
}
.wrap {
flex-wrap: wrap;
}
body {
background: #ebebeb;
font-size: 1.25em;
font-family: 'Open Sans', sans-serif;
}
.container {
height: 100vh;
justify-content: space-around;
}
.component {} .primary {
background: red;
height: 150px;
width: 200px;
margin-right: 30px;
}
.secondary {
background: blue;
height: 100px;
width: 200px;
margin-left: 30px;
}
@media (max-width: 600px) {}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container flex row wrap">
<div class="component flex column">
<div class="primary"></div>
<div class="secondary"></div>
</div>
<div class="component flex column">
<div class="primary"></div>
<div class="secondary"></div>
</div>
<div class="component flex column">
<div class="primary"></div>
<div class="secondary"></div>
</div>
<div class="component flex column">
<div class="primary"></div>
<div class="secondary"></div>
</div>
</div>
<!--container-->
答案 1 :(得分:2)
在javascript中使用事件传播机制
var theParent = document.querySelector("#idOfParent");
theParent.addEventListener("mouseenter", doYourStuffforMouseEnterEvent,false);
theParent.addEventListener("mouseleave", doYourStuffforMouseLeaveEvent,false);
function doYourStuffforMouseEnterEvent(e) {
if (e.target !== e.currentTarget) {
var Item = e.target.id;
alert("This item is the current hover item " + Item );
$(".primary").css({"margin-right":"0", "transition":"1s"});
$(".secondary").css({"margin-left":"0", "transition":"1s"});
});
}
e.stopPropagation();
}
function doYourStuffforMouseLeaveEvent(e) {
if (e.target !== e.currentTarget) {
var Item = e.target.id;
alert("This item is the current hover item " + Item );
$(".primary").css({"margin-right":"30px", "transition":"1s"});
$(".secondary").css({"margin-left":"30px", "transition":"1s"});
});
}
e.stopPropagation();
}