在Vue中鼠标悬停时表格行的背景颜色

huangapple go评论98阅读模式
英文:

Mouseover tablerow background color in VUE

问题

我正在尝试在VUE中更改表格行的背景颜色。我希望当鼠标悬停在表格行上时,将其背景颜色更改为黑色,当鼠标离开时,将其恢复为默认颜色。表格行已经具有一个条件。然而,我仍在尝试类似以下的内容:

<tr v-for="row in Object.keys(tidyMarketOrders)" v-bind:key="row.ticker" @onmouseover="color='black'">
英文:

I am trying to change the background color on a Table row in VUE. I want the background color of the table row to be changed to black when the mouse is hovered and back to default when it is not. The table row already has a condition on it. However I am still trying something like this

&lt;tr v-for=&quot;row in Object.keys(tidyMarketOrders)&quot; v-bind:key=&quot;row.ticker&quot; @onmouseover=&quot;color=&#39;black&#39;&quot;&gt;

答案1

得分: 1

@onmouseover 期望一个 JavaScript 语句或函数。当鼠标悬停在表格行上时,您将字符串 &#39;black&#39; 分配给名为 color 的变量。由于这个变量与 &lt;tr&gt; 没有任何关系,它并没有实现任何功能。

您可以使用 CSS 来实现您的目标。

tr:hover {
  background-color: black;
}

如果您绝对必须以编程方式执行此操作,您可以这样做:

&lt;template&gt;
  &lt;tr
    :style=&quot;{ backgroundColor: bgColor }&quot;
    @mouseover=&quot;bgColor = &#39;black&#39;&quot;
    @mouseleave=&quot;bgColor = &#39;white&#39;&quot;
  &gt;
    &lt;td&gt;表格行内容&lt;/td&gt;
  &lt;/tr&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  data() {
    return {
      bgColor: &#39;white&#39;
    }
  }
}
&lt;/script&gt;

您需要使用 @mouseleave 来执行与 @mouseenter 相反的操作,以模拟切换效果。还要注意事件名称不包括单词 "on"。在 Vue 中,您可以省略它,例如 onclick 只需写成 @click

英文:

@onmouseover expects a JavaScript statement or function. On mousing over the table row you're assigning the string &#39;black&#39; to a variable called color. Since this variable is not related to the &lt;tr&gt; in any way it doesn't accomplish anything.

You can accomplish your goal instead with CSS.

tr:hover {
  background-color: black;
}

If you absolutely had to do this programmatically, you could do something like this:

&lt;template&gt;
  &lt;tr
    :style=&quot;{ backgroundColor: bgColor }&quot;
    @mouseover=&quot;bgColor = &#39;black&#39;&quot;
    @mouseleave=&quot;bgColor = &#39;white&#39;&quot;
  &gt;
    &lt;td&gt;table row content&lt;/td&gt;
  &lt;/tr&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  data() {
    return {
      bgColor: &#39;white&#39;
    }
  }
}
&lt;/script&gt;

You'll need @mouseleave to do the opposite of @mouseenter to simulate a toggle effect. Also notice that the event names don't include the word "on". In Vue you omit that, so for example onclick is just @click

huangapple
  • 本文由 发表于 2023年6月5日 06:50:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76402708.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定