Chrome扩展..从JS执行CSS

Chrome extension...execute CSS from JS?

本文关键字:执行 CSS JS 扩展 Chrome      更新时间:2023-09-26

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

清单.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"
   ]
}

背景。JS

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

内容.JS

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

旋转CSS

@keyframes spin {
    from {transform:rotate(0deg);}
    to {transform:rotate(360deg);}
}
.animation {
    animation: 40s spin infinite linear;
}

请更换

el.addClass("animation");

带有

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