当鼠标悬停在按钮上时,我无法更改描边的颜色。我试过自己解决,但我做不到。
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;
}
}
}
要回答为什么您的代码不起作用的问题:您在开始时只渲染 Canvas 一次。要更改它,您必须在 button1hover()
和 button1unhover()
中使用相应的颜色重新渲染它。
即便如此,document.getElementById("one").style.backgroundColor == "#3d7eb8"
也不能保证有效。因为,根据浏览器的不同,.style.backgroundColor
可能会将颜色返回为 rgb(...)
值。
所以最好定义一个变量来存储状态并切换/检查它。
关于javascript - 无法从 javascript 更改颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57236305/