[英]how can I change css within a nested jQuery function
我正在尝试创建一个元素,当鼠标悬停在其图像上时,该元素会更改,并且其位置也会相应调整。 但是图像在变化,但css位置没有变化。
jQuery / JavaScript:
var newComment = $('<span>').attr({'id': commentCount});
newComment
.addClass('comment')
.css({
'top': (yOffset * 100) + 175 + "px",
'left': (xOffset * 75) + 40 + "px"
})
.hover(function(){ //Hover over the comment
newComment
.removeClass()
.addClass('commentOver')
.offset({
'top': yOffsets[newComment.id] + 175 - 1250 + "px",
'left': xOffsets[newComment.id] + 40 - 1500 + "px"
});
},function(){ //Mouse leaves the comment
newComment
.removeClass()
.addClass('comment')
.offset({
'top': yOffsets[newComment.id] + 1750 + "px",
'left': xOffsets[newComment.id] + 400 + "px"
});
});
CSS:
.comment{
position: absolute;
z-index: 10;
padding: 0px;
width: 51px;
height: 70px;
background-image: url('../img/dropSmall.png');
font-weight:800;
}
您能看到我要去哪里哪里以及为什么吗?
newComment范围是否已添加到文档中?
由于我们没有剩下的HTML / CSS /代码,所以我不知道这些是否是唯一的问题,但是我建议使用$(this)并在removeClass()中传递参数:
var newComment = $('<span>').attr({'id': commentCount});
newComment
.addClass('comment')
.css({
'top': (yOffset * 100) + 175 + "px",
'left': (xOffset * 75) + 40 + "px"
})
.hover(function(){ //Hover over the comment
$(this)
.removeClass("comment")
.addClass('commentOver')
.offset({
'top': yOffsets[newComment.id] + 175 - 1250,
'left': xOffsets[newComment.id] + 40 - 1500
});
},function(){ //Mouse leaves the comment
$(this)
.removeClass("commentOver")
.addClass('comment')
.offset({
'top': yOffsets[newComment.id] + 1750,
'left': xOffsets[newComment.id] + 400"
});
});
我在jQuery文档中看不到可以在不传递任何参数的情况下调用removeClass()的情况。 它说您需要一个或多个课程。
另外,如果单位是px,则offset()方法不需要单位。
您可能还想看看toggleClass(“ a”,“ b”) ,这使得交换两个类变得容易。
您是否将元素newComment
定位为absolute
? 如果元素定位为static
则不能使用top和left。
如果没有,请尝试使用此方法,而不要使用当前的.css
:
.css({
'top': (yOffset * 100) + 175 + "px",
'left': (xOffset * 75) + 40 + "px",
'position': 'absolute'
})
顺便说一句:使用DOM编写时,不必将css属性的名称作为字符串传递。 因此,这应该是一样的:
.css({
top: (yOffset * 100) + 175 + "px",
left: (xOffset * 75) + 40 + "px",
position: 'absolute'
})
删除偏移量对象参数末尾的“ px”;)
.offset({
'top': yOffsets[newComment.id] + 175 - 1250,// + "px",
'left': xOffsets[newComment.id] + 40 - 1500// + "px"
});
如果offset方法无法将left
和top
属性识别为数字,则不会更新元素位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.