在我的来源中,我有: 在样式部分:
<head>
<style>
.grayableDiv{background-color:transparent}
</style>
</head>
<script>
function DoGrayEffectIn()
{
$('.grayableDiv').css('background-color', 'Gray');
}
function DoGrayEffectOut()
{
$('.grayableDiv').css('background-color', 'Transparent');
}
</script>
<div class="grayableDiv" onmouseover ="DoGrayEffectIn" onmouseout="DoGrayEffectOut">
但是当用鼠标滑过div时我看不到效果。 我究竟做错了什么。是否有可能以这种方式混合jquery和javascript?
答案 0 :(得分:2)
您需要在事件处理程序中添加括号()
,以便调用它们的函数。
应该是onmouseover ="DoGrayEffectIn()"
,而不是onmouseover ="DoGrayEffectIn"
Stack snippet
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
.grayableDiv {
background-color: transparent
}
</style>
</head>
<script>
function DoGrayEffectIn() {
$('.grayableDiv').css('background-color', 'Gray');
}
function DoGrayEffectOut() {
$('.grayableDiv').css('background-color', 'Transparent');
}
</script>
<div class="grayableDiv" onmouseover="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">div</div>
将JavaScript附加到网站前端的更好做法是将其与标记分开,通常称为unobtrusive javascript。
Stack snippet
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<style>
.grayableDiv {
background-color: transparent
}
</style>
</head>
<script>
$(document).ready(function() {
$('.grayableDiv')
.mouseover(function() {
$(this).css('background-color', 'Gray');
}).mouseout(function() {
$(this).css('background-color', 'Transparent');
});
});
</script>
<div class="grayableDiv">div</div>
答案 1 :(得分:1)
您没有使用()
调用该函数<div class="grayableDiv" onmouseover ="DoGrayEffectIn()" onmouseout="DoGrayEffectOut()">
答案 2 :(得分:1)
<script>
$(document).ready(function(){
$(".grayableDiv").mouseover(function(){
$(".grayableDiv").css("background-color", "gray");
});
$(".grayableDiv").mouseout(function(){
$(".grayableDiv").css("background-color", "transparent");
});
});
</script>