如何在页面加载时自动分配值,而无需调用悬停或单击任何事件操作。颜色将根据用户输入或随机颜色进行更改,将自动生成悬停容器“someclass”将对所有人都相同。
<div class="container1">
<div class="someclass"> " #ffff13 " </div>
</div>
<div class="container2">
<div class="someclass"> " #ffff15 " </div>
</div>
<div class="somecontainer">
<div class="someclass"> " #ffgf19 " </div>
</div>
<div class="thecontainer">
<div class="someclass"> " #0fff1a " </div>
</div>
<div class="container1">
<div class="someclass"> " #cfff17 " </div>
</div>
<div class="mastercontainer10">
<div class="someclass"> " #1fff13 " </div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(".someclass").hover(
function() {
var color = /#[0-9\A-F]+/.exec($(this).html())[0];
$(this).css('background', color)
}, function() {
$(this).css('background', color)
});
});
</script>
答案 0 :(得分:1)
尝试将悬停功能放在匿名函数中
(function() {
// insert code here
})(); // anonymous function
答案 1 :(得分:1)
你在找这个吗?
(function () {
$(".someclass").each(function () {
var html = $(this).html();
var color = html;
$(this).css('background', color);
});
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someclass">#ffff13</div>
<div class="someclass">#ffff25</div>
<div class="someclass">#ffff36</div>
<div class="someclass">#ffff48</div>
<div class="someclass">#ffff50</div>
<div class="someclass">#87CEEB</div>
&#13;
你想看这个
(function () {
var color;
$(".someclass").hover(function () {
var html = $(this).html();
color = html;
this.style.backgroundColor = color
});
$(".someclass").mouseleave(function () {
this.style.backgroundColor = "white"
});
})();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="background-color:white;" class="someclass">#ffff13</div>
<div style="background-color:white;" class="someclass">#ffff25</div>
<div style="background-color:white;" class="someclass">#ffff36</div>
<div style="background-color:white;" class="someclass">#ffff48</div>
<div style="background-color:white;" class="someclass">#ffff50</div>
<div style="background-color:white;" class="someclass">#87CEEB</div>
&#13;