【问题标题】:Chrome extension...execute CSS from JS?Chrome 扩展...从 JS 执行 CSS?
【发布时间】:2016-01-04 14:31:17
【问题描述】:

我正在制作一个 Chrome 扩展程序,我想使用 CSS 关键帧动画使页面上的所有图像旋转,但我也希望它使用 JS 打开/关闭。我已经想出了如何打开和关闭,但是我应该如何从 JS 执行 CSS?我能想到的只是找到所有图像,并添加.animation 类,但它似乎不起作用。

ma​​nifest.JSON

{
  "manifest_version": 2,

  "name": "SPINS",
  "description": "SPINS",
  "version": "1.0",
  "browser_action": { },

  "icons": { "16": "icon16.png",
           "48": "icon48.png",
          "128": "icon128.png" },

  "background": {
    "scripts": ["background.js"]
  },

  "content_scripts": 
    [{
      "matches": ["<all_urls>"],
      "css": [ "spin.css"],
      "js": [ "content.js"]
      }],



  "permissions": [
   "activeTab"
   ]
}

background.JS

chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.sendMessage(tab.id,{});
});

content.JS

var toggle = false;
chrome.runtime.onMessage.addListener(function() {
  toggle = !toggle;
  Array.prototype.forEach.call(document.querySelectorAll('img'), function(el) {
    el.addClass("animation");
  });
});

spin.CSS

@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}

.animation {
    animation: 40s spin infinite linear;
}

【问题讨论】:

  • 为什么使用Array.prototype.forEach.call()?一个简单的document.getElementsByTagName() 和 for 循环不会解决问题吗?
  • @AndrueAnderson 也许对函数式的forEachfor (;;) 循环有强烈的偏好
  • @ooohfff,您需要更好地解释“执行 CSS”的含义。

标签: javascript css google-chrome google-chrome-extension


【解决方案1】:

请更换

el.addClass("animation");

el.className = el.className + " animation";

【讨论】:

    猜你喜欢
    • 2012-03-10
    • 2013-03-09
    • 2013-11-15
    • 2013-11-23
    • 2012-05-09
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多