首页 > 解决方案 > 只需指向鼠标即可更改对象的颜色

问题描述

我想通过将箭头(鼠标指针)指向圆圈(无点击)将圆圈的颜色从绿色变为红色。但是对于红色圆圈,人必须点击圆圈来改变颜色。每次单击或悬停在屏幕上时,圆圈也应更改其位置。

基本上,红点 - 点击,绿点 - 不要点击。两种颜色应随机交替,但红色圆圈应弹出更多,比例为 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', 
  });
});

标签: javascripthtmlcssnode.js

解决方案


用基本的 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>


推荐阅读