javascript - 在 insertRule javascript 语句中格式化字符串

标签 javascript jquery css

我希望使用 insertRule 通过 Javascript 更改导航元素的 :hover 样式。导航链接的背景颜色将根据 bgndImgIndex 发生变化。这可以用 Javascript 实现还是我完全错了?

var bgndImgIndex = 0;
var colorSelect = ['#ffa800', '#ba2a2a', '#5ad339'];

var sheet = document.styleSheets[0];

sheet.insertRule("a:hover {background:{0} !important".format(colorSelect[bgndImgIndex]), 4);

最佳答案

这完全有可能。问题似乎是 .format 在 JS 的 String 原型(prototype)上不存在。我通常在 JS 中使用 ES6 模板字符串来完成这个任务,请看工作示例:

var bgndImgIndex = 0;
var colorSelect = ['#ffa800', '#ba2a2a', '#5ad339'];

var sheet = document.styleSheets[0];

sheet.insertRule(
  `a:hover {background:${colorSelect[bgndImgIndex]} !important`
);
<a>Test</a>

关于javascript - 在 insertRule javascript 语句中格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40823161/

相关文章:

jQuery - 无法解析 json

jquery - $.ajax()优先级

javascript - 无法在文档正文上调用 ajaxSubmit 函数

javascript - ng-if 没有捕获更新的 $scope 值

javascript - jQuery 似乎没有克隆事件,而只是克隆 html/xml?

css - 使用 Bootstrap/CSS 缩放不同大小的图像

php - 如何在多个网页上显示导航栏?

javascript - 数组 : required, 中的变量是一种很好的做法,还是多余的?

javascript - 在两个 View 中使用 Angular JS 的 Ionic 应用程序的动态列表

html - CSS 溢出 : auto in some elements don't work