gpt4 book ai didi

javascript - 如何使用 onclick 更改 div 迭代数组中的字体?

转载 作者:行者123 更新时间:2023-11-30 14:26:34 26 4
gpt4 key购买 nike

我有一个数组,我迭代它以便将文本放置在网页上单独的 div 中(稍后我为 div 设置动画)。我想为每个 div 添加一个 onclick,因此当单击 div/text 时,字体粗细会发生变化。我至少知道一种在更简单的情况下使用 onclick 的方法:

<div class="nameDiv" id="div1" onclick='boldText(this, this.id);'>Test</div>

<script>
function boldText(txt, txtid){
var el = document.getElementById(txtid);
var fontstyle = window.getComputedStyle(el, null).fontWeight;

if (fontstyle != '800') {
txt.style.fontWeight = '800';
} else {
txt.style.fontWeight = '300';
}

}
</script>

但是,我无法通过迭代在我的代码中使用相同类型的东西。

var setNames = function() {
var h = 0;
for(var n = 0; n < numberStudents; n++){
var divName = "floatName" + n;
var names = nameArray[n].fields.nickname; <!-- gets the text/name for each div -->
var divTag = document.createElement('div');
divTag.id = divName;
divTag.innerHTML = names;
divTag.className = "randomFloat";

// try to give each div an onclick
divTag.onclick = boldText(this, this.id);

studentCol.appendChild(divTag); <!-- attach to studentCol/'anchor'/parent element -->
};
};

setNames();

function boldText(txt, txtid){ <!-- pass both the object and the object id -->
var el = document.getElementById(txtid);

// I've tried both lines below -->
var fontstyle = window.getComputedStyle(el, null).fontWeight; <!-- gives me an error saying el is not an object -->

//var fontstyle = window.getComputedStyle(el, null).fontWeight;
// line above gives TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element -->

if (fontstyle != '300') {
txt.style.fontWeight = '300';
} else {
txt.style.fontWeight = '800';
}

};

可不可以每个divTag.id都有一个单独的onclick?如果是这样,我需要更改我的代码中的哪些内容?

最佳答案

问题是您分配的是 boldText 函数结果而不是函数本身。请试试这个:

divTag.onclick = boldText;

通过这种方式,您可以在 boldText 函数中访问 this,无需向其传递任何参数。例如

this.style.fontWeight = '300';

关于javascript - 如何使用 onclick 更改 div 迭代数组中的字体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51829486/

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