javascript - 无法从javascript更改颜色
问题描述
将鼠标悬停在按钮上时,我无法更改笔触的颜色。我试过自己解决,但我做不到。
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.moveTo(17, 7);
ctx.bezierCurveTo(13, -8, 26, 21, 12, 26);
ctx.bezierCurveTo(-2, 31, 59, 64, 33, 18);
ctx.lineWidth = 8;
ctx.strokeStyle = "#3d7eb8";
if (document.getElementById("one").style.backgroundColor == "#3d7eb8"){
ctx.strokeStyle = "#fffced";
}
ctx.stroke();
function button1hover (){
document.getElementById("one").style = "background-color: #3d7eb8";
}
function button1unhover (){
document.getElementById("one").style = "background-color: #fffced";
}
<button onmouseout="button1unhover()" onmouseover="button1hover()" id="one" class="button column center">
<canvas height="50px" width="50px" id="canvas1"></canvas>
<p>Inici</p>
</button>
解决方案
这真的不是 JS 的工作,这一切都可以通过 CSS 和一个用于曲线的小内联 SVG 来完成。
#one {
background-color: #fffced;
}
#one svg {
width: 50px;
height: 50px;
}
#one:hover {
background-color: #3d7eb8;
}
#one path {
fill: none;
stroke-width: 8px;
stroke: #3d7eb8;
}
#one:hover path {
stroke: #fffced;
}
<button id="one" class="button column center">
<svg><path d="M 17 7 C 13 -8 26 21 12 26 -2 31 59 64 33 18" /></svg>
<p>Inici</p>
</button>
如果你使用 less 或 sass/scss,甚至 CSS 会更好
#one {
background-color: #fffced;
svg {
width: 50px;
height: 50px;
}
path {
fill: none;
stroke-width: 8px;
stroke: #3d7eb8;
}
&:hover {
background-color: #3d7eb8;
path {
stroke: #fffced;
}
}
}
要回答为什么您的代码不起作用的问题:您在开始时只渲染一次画布。要更改它,您必须在内部重新渲染它button1hover()
并button1unhover()
使用相应的颜色。
即使那样,document.getElementById("one").style.backgroundColor == "#3d7eb8"
也不能保证工作。因为,取决于浏览器,.style.backgroundColor
可能会将颜色作为rgb(...)
值返回。
所以最好定义一个存储状态的变量并切换/检查它。
推荐阅读
- php - Google App Engine - 第一个请求很慢
- regex - 域名过滤器的 Nginx 正则表达式问题
- java - [spark-cassandra-connector]如何在spark 2.3.1中将scala隐式支持的代码转换为java
- apache-kafka - Kafka 代理对大量消费者群体的影响
- python - 如何在 Python 中找到两个市场参与者(企业设定价格和政府设定消费税)的市场均衡?
- ios - 从领域获取“不允许向领域添加已删除或无效的对象”
- c# - 如何计算 IEnumerator 中的元素数量?
- python - ValueError:从字典制作 DataFrame 时无法从重复的轴重新索引
- node.js - 节点时刻 - 特定时区的 endOf('day')
- javascript - Service Worker:如何使用 Workbox 缓存没有扩展的图像