【发布时间】:2016-01-04 14:31:17
【问题描述】:
我正在制作一个 Chrome 扩展程序,我想使用 CSS 关键帧动画使页面上的所有图像旋转,但我也希望它使用 JS 打开/关闭。我已经想出了如何打开和关闭,但是我应该如何从 JS 执行 CSS?我能想到的只是找到所有图像,并添加.animation 类,但它似乎不起作用。
manifest.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 也许对函数式的
forEach比for (;;)循环有强烈的偏好 -
@ooohfff,您需要更好地解释“执行 CSS”的含义。
标签: javascript css google-chrome google-chrome-extension