[英]javascript one click select / deselect text in a div
我想添加一個按鈕,該按鈕將使用 javascript 選擇/取消選擇 div 中的文本。
例如,單擊一次將選擇文本,下一次單擊將取消選擇文本等等。
如果要選擇/取消選擇,只需將點擊處理程序調整為以下內容:
<span rel="theDiv">select text of div</span>
<div id="theDiv">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
</div>
$('span').click(function() {
var targetDiv = $(this).toggleClass("selected").attr("rel");
if($(this).hasClass("selected")){
SelectText(targetDiv);
}
});
我是這樣的:
HTML:
<div id="div-configure-buttons-wrapper">
<button type="button" id="grid-config-button-1" class="grid-configure-buttons" active=false>1x</button>
<button type="button" id="grid-config-button-2" class="grid-configure-buttons" active=false>2x</button>
<button type="button" id="grid-config-button-3" class="grid-configure-buttons" active=false>4x</button>
<button type="button" id="grid-config-button-4" class="grid-configure-buttons" active=false>6x</button>
<button type="button" id="grid-config-button-5" class="grid-configure-buttons" active=false>8x</button>
</div>
JS:
const setOfBtn = document.querySelectorAll('.div-configure-buttons'); //Div with 5 buttons, but it can have as many as you want
setOfBtn.forEach(val => { // "val" is each button found in setOfBtn
val.addEventListener('click', () => {
switchActive() // calls a function to set "false" in "active" property of all buttons.
val.active = !val.active //now, with all buttons set as "false", the clicked button will be the only one with "true"
isBtnActive(val) // set backgroundColors for the "true"/selected button
console.log(val.active);
});
function switchActive(){
setOfBtn.forEach(val => {
if(val.active === true){
val.active = false
isBtnActive(val)
console.log(val)
}
})
}
function isBtnActive(val){ // just setting a backgroundColor for the "true"/selected button and removing the backgroundColor of the previous selected button
if(val.active){
document.getElementById(val.id).style.backgroundColor = 'blue'
val.setAttribute('active', val.active)
console.log(val);
}else{
document.getElementById(val.id).style.backgroundColor = 'white'
val.setAttribute('active', val.active)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.