简体   繁体   English

jQuery:使用选择中的颜色更改mousemove上div的背景颜色

[英]jQuery: Change background color of div on mousemove with colors from selection

I want to set about four colors, and use them for the background color of a div.我想设置大约四种颜色,并将它们用于 div 的背景颜色。 There should be a smooth transition from one color to the next while moving the cursor.移动光标时,应该从一种颜色平滑过渡到另一种颜色。

My idea looks like that:我的想法是这样的:

 $(document).mousemove(function(e) { let path = ["blue", "orange", "red", "green"] if ($pageX <= $pageY) { //??? } $("div").css('background-color', path); });
 div { width: 300px; height: 300px; background-color: #e57266; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="color-area"></div>

But every try failed.但每次尝试都失败了。 I would be soooo thankful for help!我会非常感谢您的帮助! :) :)

I can suggest such a solution.我可以建议这样的解决方案。 Add transition: .1s for div tag to smoothly change the color.div标签添加transition: .1s以平滑更改颜色。

 $(document).mousemove(function(e) { let path = ["blue", "orange", "red", "green"] $("div").css('background-color', path[Math.floor(Math.random() * path.length)]); });
 div { width: 300px; height: 300px; background-color: #e57266; transition: .1s; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="color-area"></div>

Try this:尝试这个:

A small modification to @sergey's answer@sergey 的回答的一个小修改

 $(document).mousemove(function(e) { let path = ["blue", "orange", "red", "green"] $("div").css('background-color', path[Math.floor(Math.random() * path.length)]); });
 div { width: 300px; height: 300px; background-color: #e57266; transition: background 1s; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="color-area"></div>

You can change the transition if you want it faster如果你想更快,你可以改变过渡

Edit编辑

@sergey managed to answer a few minutes before me! @sergey设法比我早几分钟回答!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM