这可能是一个非常明显的问题,我只是坚持了一段时间,在网上找不到任何东西。现在我有以下(非常简单)html div:
<div class="unselected"
onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='??' >
在我的webapp中,我动态更改div的类(在selected和unselected之间更改div的背景颜色)。有没有办法将onmouseout backgroundColor更改为类的默认背景颜色(如样式表中所定义)?
换句话说,我正在寻找像
这样的东西onmouseout="this.style.backgroundColor=this.class.default-background-color
这可能吗?对于每个站点来说,这似乎几乎是必要的(除非他们想要在两个地方而不仅仅是样式表中更改颜色),但是没有在线指南似乎可以解决它。
非常感谢!
答案 0 :(得分:5)
你应该使用一种不引人注目的方式,添加&amp;删除css类:
的CSS:
.yellow {
background-color: yellow !important;
}
$(function() {
$('div.unselected').hover(function() {
$(this).addClass('yellow');
}, function() {
$(this).removeClass('yellow');
});
});
答案 1 :(得分:2)
最好的方法就是上课。
首先,创建一个yellowBg
类:
.yellowBg {
background-color: #0ff;
}
然后使用jQuery在mouseover上应用它并在mouseout上删除它:
$(document).ready(function(){
$('.unselected').mouseover(function(){
$(this).addClass('yellowBg');
}).mouseout(function(){
$(this).removeClass('yellowBg');
});
});
答案 2 :(得分:1)
$('.unselected').hover(function(){ //mouseout
// if not has data-origColor
if(!$(this).data('origColor'))
$(this).data('origColor', this.style.backgroundColor);
this.style.backgroundColor = 'yellow';
}, function(){ //mouseover
this.style.backgroundColor = $(this).data('origColor'); //pull from data
});
答案 3 :(得分:0)
将属性设置为空字符串,以从样式属性外部恢复为级联。
<div class="unselected"
onmouseover="this.style.backgroundColor='yellow'"
onmouseout="this.style.backgroundColor='' >
(但是,一般来说,尝试将样式保留在样式表中而不是样式属性和JS(使用JS来设置类)并尝试将JS保存在外部文件中,事件处理程序不显眼地应用而不是使用内在函数事件属性)