gpt4 book ai didi

javascript - 将 getElementById 替换为 getElementsByClassName

转载 作者:行者123 更新时间:2023-12-03 06:45:54 25 4
gpt4 key购买 nike

我想修改下面的JavaScript以按类名称而不是元素ID进行选择:

https://github.com/sarathsaleem/grained/blob/master/grained.js

然后理想情况下进行初始化,如下所示:

grained(".classname", options);

最佳答案

Sarath Saleem 的grained.js 的这个修改版本获取具有给定类名选择器(即“.foo”)的所有元素,并为它们提供指定的噪声背景。我没有对这段代码进行太多测试,所以从效率上来说它绝对不是生产质量的。关键是将 element 变量更改为 elements 并使用 document.getElementsByClassName,其中新命名的 elements > 变量已定义。这将返回具有给定类(即“foo”)的所有 HTML 元素的 HTMLCollection。然后,在设置元素的 positionoverflow 属性的部分,使用 for 循环并迭代 HTMLCollection 以设置 position 和具有给定类的每个找到的元素的 overflow 属性。
注意:grained.js 文件的底部是我调用grained 函数的地方。

此外,我还调整了使用先前命名的 elementId 变量的位置,以使用基于给定类名的新 elementClass 变量。

您可以在grained.js iife 之后的任何位置执行此操作,因为它位于之后的全局命名空间中。

/*! Grained.js
* Author : Sarath Saleem - https://github.com/sarathsaleem
* MIT license: http://opensource.org/licenses/MIT
* GitHub : https://github.com/sarathsaleem/grained
* v0.0.1
*/
(function (window, doc) {

"use strict";

function grained(ele, opt) {

var elements = null,
elementClass = null,
selectorElement = null;

//1
if (typeof ele === 'string') {
elements = doc.getElementsByClassName(ele.split('.')[1]);
}
//1
if (!elements) {
console.error('Grained: cannot find any elements with class ' + ele);
return;
} else {
elementClass = elements[0].className;
}

var elementsLength = elements.length
for( var i = 0; i < elementsLength; i++) {
//set style for parent
if (elements[i].style.position !== 'absolute') {
elements[i].style.position = 'relative';
}
elements[i].style.overflow = 'hidden';
};

var prefixes = ["", "-moz-", "-o-animation-", "-webkit-", "-ms-"];

//default option values
var options = {
animate: true,
patternWidth: 100,
patternHeight: 100,
grainOpacity: 0.1,
grainDensity: 1,
grainWidth: 1,
grainHeight: 1,
grainChaos: 0.5,
grainSpeed: 20

};

Object.keys(opt).forEach(function (key) {
options[key] = opt[key];
});


var generateNoise = function () {
var canvas = doc.createElement('canvas');
var ctx = canvas.getContext('2d');
canvas.width = options.patternWidth;
canvas.height = options.patternHeight;
for (var w = 0; w < options.patternWidth; w += options.grainDensity) {
for (var h = 0; h < options.patternHeight; h += options.grainDensity) {
var rgb = Math.random() * 256 | 0;
ctx.fillStyle = 'rgba(' + [rgb, rgb, rgb, options.grainOpacity].join() + ')';
ctx.fillRect(w, h, options.grainWidth, options.grainHeight);
}
}
return canvas.toDataURL('image/png');
};

function addCSSRule(sheet, selector, rules, index) {
var ins = '';
if (selector.length) {
ins = selector + "{" + rules + "}";
} else {
ins = rules;
}

if ("insertRule" in sheet) {
sheet.insertRule(ins, index);
} else if ("addRule" in sheet) {
sheet.addRule(selector, rules, index);
}
}


var noise = generateNoise();

var animation = '',
keyFrames = ['0%:-10%,10%', '10%:-25%,0%', '20%:-30%,10%', '30%:-30%,30%', '40%::-20%,20%', '50%:-15%,10%', '60%:-20%,20%', '70%:-5%,20%', '80%:-25%,5%', '90%:-30%,25%', '100%:-10%,10%'];

var pre = prefixes.length;
while (pre--) {
animation += '@' + prefixes[pre] + 'keyframes grained{';
for (var key = 0; key < keyFrames.length; key++) {
var keyVal = keyFrames[key].split(':');
animation += keyVal[0] + '{';
animation += prefixes[pre] + 'transform:translate(' + keyVal[1] + ');';
animation += '}';
}
animation += '}';
}

//add animation keyframe
var animationAdded = doc.getElementById('grained-animation');
if (animationAdded) {
animationAdded.parentElement.removeChild(animationAdded);
}
var style = doc.createElement("style");
style.type = "text/css";
style.id = 'grained-animation';
style.innerHTML = animation;
doc.body.appendChild(style);

//add custimozed style
var styleAdded = doc.getElementById('grained-animation-' + elementClass);
if (styleAdded) {
styleAdded.parentElement.removeChild(styleAdded);
}

style = doc.createElement("style");
style.type = "text/css";
style.id = 'grained-animation-' + elementClass;
doc.body.appendChild(style);

var rule = 'background-image: url(' + noise + ');';
rule += 'position: absolute;content: "";height: 300%;width: 300%;left: -100%;top: -100%;';
pre = prefixes.length;
if (options.animate) {
while (pre--) {
rule += prefixes[pre] + 'animation-name:grained;';
rule += prefixes[pre] + 'animation-iteration-count: infinite;';
rule += prefixes[pre] + 'animation-duration: ' + options.grainChaos + 's;';
rule += prefixes[pre] + 'animation-timing-function: steps(' +options.grainSpeed + ', end);';
}
}

//selecter element to add grains
selectorElement = '.' + elementClass + '::before';


addCSSRule(style.sheet, selectorElement, rule, 0);


}

window.grained = grained;
//END
})(window, document);

grained('.foo', {});
<!doctype html>
<html>
<head>
<title>Example</title>
<style>
.foo {
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<div class="foo">
<div class="contents">
<p>Hello World</p>
</div>
</div>
<p>No Noise For Me!</p>
<div class="foo">
<div class="contents">
<p>Hello World</p>
</div>
</div>

<script type="text/javascript" src="grained.js"></script>
<script type="text/javascript" src="index.js"></script>
</body>
</html>

希望这有帮助!如果您有任何疑问,请询问!我喜欢提供帮助:D。

关于javascript - 将 getElementById 替换为 getElementsByClassName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37738367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com