javascript - 只需指向鼠标即可更改对象的颜色
问题描述
我想通过将箭头(鼠标指针)指向圆圈(无点击)将圆圈的颜色从绿色变为红色。但是对于红色圆圈,人必须点击圆圈来改变颜色。每次单击或悬停在屏幕上时,圆圈也应更改其位置。
基本上,红点 - 点击,绿点 - 不要点击。两种颜色应随机交替,但红色圆圈应弹出更多,比例为 65/35。
代码采用 HTML、CSS 和 JavaScript (JS)
该演示目前看起来像这样:https ://jsfiddle.net/sidsingh29/591hfwLd/20/
第二种解决方案:如果这不可能或太复杂,我只想让所有点在 1 秒后消失而没有任何触发。在这个红色和绿色圆圈中,都会在 1 秒内自动消失,但红色圆圈会更频繁地弹出,红绿比例为 65/35。此外,当颜色变化时,圆圈的位置也应该在屏幕上更改为屏幕上的任何随机点。我们需要确保圆圈不超出屏幕宽度/大小。
** 代码 **
HTML:
<div id="test"></div>
CSS:
#test {
position:absolute;
height: 70px;
width: 100px;
background-color: red;
border-radius: 50%;
display: inline-block;}
JavaScript + jQuery (edge):
$('#test').click(function() {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
background: Math.random() > 0.3 ? 'red' : 'green',
});
});
解决方案
用基本的 CSS 来制作。
#test {
position:absolute;
height: 70px;
width: 100px;
background-color: green;
border-radius: 50%;
display: inline-block;
}
#test:hover {
background-color : red;
}
<div id="test"></div>
如果您想在元素悬停时执行 JS,请使用.hover()
而不是click()
在您的代码中。您还可以检测该点当前是红色还是绿色if (div.style.backgroundColor == "red")
这段代码可能不会像您期望的那样工作,因为我不了解您想要做什么,但它应该给您和想法。
$('#test').click(function() {
if (document.getElementById("test").style.backgroundColor != "green") {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
background: Math.random() > 0.3 ? 'red' : 'green',
});
}
});
$('#test').hover(function() {
if (document.getElementById("test").style.backgroundColor == "green" && $('#test').is(":hover")) {
var docHeight = $(document).height(),
docWidth = $(document).width(),
$div = $('#test'),
divWidth = $div.width(),
divHeight = $div.height(),
heightMax = docHeight - divHeight,
widthMax = docWidth - divWidth;
$div.css({
left: Math.floor( Math.random() * widthMax ),
top: Math.floor( Math.random() * heightMax ),
background: Math.random() > 0.3 ? 'red' : 'green',
});
}
});
#test {
position:absolute;
height: 70px;
width: 100px;
background-color: red;
border-radius: 50%;
display: inline-block;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test"></div>
推荐阅读
- android - 如何使用改造发布整数列表?
- visual-studio-code - 为所有用户安装 vscode
- c# - 通用 Windows 平台和 .net 核心兼容性
- javascript - Uncaught TypeError: (...).modal 不是 ES6 中的函数
- typescript - 打字稿歧视联盟允许无效状态
- github - 带有 github 页面和 jekyll 的自定义名称域
- php - 管理员用户列表自定义列显示基于 Wordpress 中的自定义用户元数据
- php - 有条件地将键/值对添加到 Woocommerce 中的数组
- javascript - 查找 JSON 的最大值并存储为变量
- php - 如何在 laravel 控制器中访问 MongoDB 游标中返回的数据?