使用JavaScript函数更改CSS中的背景颜色
使用CSS,我试图将每个元素的背景色设置为悬停时的随机颜色:使用JavaScript函数更改CSS中的背景颜色,javascript,jquery,css,Javascript,Jquery,Css,使用CSS,我试图将每个元素的背景色设置为悬停时的随机颜色: :hover { background-color: "getRandom()"; } 但是,似乎不可能在此处放置JavaScript函数调用。有没有其他可行的方法 这是我正在处理的页面: 在jQuery代码的hover事件中调用此函数: $("*").hover( function(event) { $(this).css("background-color", getRandomColor());
:hover {
background-color: "getRandom()";
}
但是,似乎不可能在此处放置JavaScript函数调用。有没有其他可行的方法
这是我正在处理的页面:
在jQuery代码的hover
事件中调用此函数:
$("*").hover(
function(event) {
$(this).css("background-color", getRandomColor());
},
function (event) {
$(this).css("background-color", "white");
}
);
(还应删除:hover
css元素)
示例:以下是一个工作示例: 您需要在通话开始和结束时设置背景色,如下所示:
$("*").hover(
function(event) {
$(this).css('background-color', getRandomColor());
},
function (event) {
$(this).css('background-color', 'white');
}
);
具有以下功能的纯跨浏览器Javascript:
var-bgColor;
var els=document.getElementsByTagName('*');
对于(变量i=0;i
这里的随机背景代码:试试这个
$(function() {
$('*').hover(
function() { $(this).css('background-color', getRandom()); },
function() {$(this).css('background-color', '#FFF');}
);
});
你不能像那样在CSS中使用JavaScript。你的问题是什么?@zzzzBov我正在尝试将元素的背景色设置为
getRandom()
的输出,该输出返回随机颜色。
var bgColor;
var els = document.getElementsByTagName('*');
for (var i = 0; i < els.length; i++) {
if (document.addEventListener) {
els[i].addEventListener('mouseover', function (e) {
e.stopPropagation();
bgColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
this.style.backgroundColor = bgColor;
}, false);
els[i].addEventListener('mouseout', function (e) {
e.stopPropagation();
bgColor = '#FFFFFF';
this.style.backgroundColor = bgColor;
}, false);
} else {
els[i].attachEvent('mouseover', function () {
e.stopPropagation();
bgColor = '#' + Math.floor(Math.random() * 16777215).toString(16);
this.style.backgroundColor = bgColor;
});
els[i].attachEvent('mouseout', function () {
e.stopPropagation();
bgColor = '#FFFFFF';
this.style.backgroundColor = bgColor;
});
}
}
$(function() {
$('*').hover(
function() { $(this).css('background-color', getRandom()); },
function() {$(this).css('background-color', '#FFF');}
);
});