我无法让这个脚本工作。我在网上搜索,找不到任何好的答案。
$( document ).ready(function() {
$("#container").click(function(){
var color = $(this).css("background");
if(color == "#ffffff"){
$(this).css("background", "#e1e1e1");
}
else {
$(this).css("background", "#ffffff");
}
});
});
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="css/stylesheet.css" type="text/css" />
<script src="js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="js/script.js" type="text/javascript"></script>
<title>Document sans nom</title>
</head>
<body>
<div id="container">
<a href="#" class="a">Start</a>
</div>
</body>
</html>
最佳答案
因为 .css('background')
可能不会以您假设的格式返回颜色,根据浏览器的不同,它可能会返回 hexa、rgb 或 rgba 格式
$(document).ready(function () {
$("#container").click(function () {
$(this).css("background-color", function () {
var color = $(this).data("background") == '#e1e1e1' ? '#ffffff' : '#e1e1e1';
$(this).data('background', color);
return color;
});
});
});
演示:Fiddle
但更简单的解决方案是使用 toggleClass() 之类的
#container {
background-color: #ffffff;
}
#container.toggled {
background-color: #e1e1e1;
}
然后
$(document).ready(function () {
$("#container").click(function () {
$(this).toggleClass('toggled');
});
});
演示:Fiddle
关于jquery - 关于 jquery .css 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22014528/