首页 > 解决方案 > 无法从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>

标签: javascripthtmlcss

解决方案


这真的不是 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(...)值返回。

所以最好定义一个存储状态的变量并切换/检查它。


推荐阅读