我需要數百個具有不同 ID 的相同元素,以便它們可以觸發不同的歌曲,而無需手動更改其 ID。這里是 HTML、JS 和 CSS:https ://jsfiddle.net/Tylanmon/by5Lcvw0/4/ 這里只是 JS:
var Song_Name = document.createTextNode('La Marseillaise')
var div = document.createElement('div')
div.setAttribute('class', 'div')
var checkbox = document.createElement('input')
checkbox.type = 'checkbox'
checkbox.name = 'checkNAME'
checkbox.id = 'checkID'
var label = document.createElement('label')
label.id = 'nameID'
label.htmlFor = 'checkID'
label.appendChild(Song_Name)
div.appendChild(label)
div.appendChild(checkbox)
document.getElementById('songs').appendChild(div)
//
var length = label.offsetWidth
var length2 = checkbox.offsetWidth
console.log(length);
div.style.width = `${length (length2 * 2 - 5.9)}px`;
div.style.backgroundColor = 'whitte'
div.style.borderRadius = '4px'
div.style.border = `1px solid black`;
uj5u.com熱心網友回復:
請記住,您是 js 新手,所以我只展示了使用 js 部分創建的 html。如果您知道回圈是如何作業的,您可以輕松地使用它
要多次創建相同的標記,您可以執行以下操作
const mainDiv = document.querySelector("#songs")
function newTextWithCheckBox(songName,id){
let div = document.createElement("div")
div.className = "each-song"
div.id = "song-" id
div.innerHTML =
`${songName}
<input type="checkbox" />`
return div
}
// now create as many as you wanted
mainDiv.append(newTextWithCheckBox("La Marseillaise",1))
mainDiv.append(newTextWithCheckBox("La Marseillaise",2))
mainDiv.append(newTextWithCheckBox("La Marseillaise",3))
mainDiv.append(newTextWithCheckBox("La Marseillaise",4))
@font-face {
font-family: Feather;
src: url(/Font/feather.ttf);
}
.div {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
Background-color: rgb(255, 221, 221);
font-size: x-large;
}
label {
color: rgb(0, 0, 0);
font-family: 'Feather';
}
.each-song {
background:pink;
padding:15px;
border : 1px solid black;
width:max-content;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="LanguageName_French.css">
</head>
<body>
<div id="songs">
</div>
<script src="LanguageName_French.js"></script>
</body>
</html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/460803.html
標籤:javascript html css 复选框
