开发者

javascript one click select / deselect text in a div

i would like to add a button that will Select / unselect the text in开发者_如何学Pythonside a div on Click using javascript ..

in example one click will select the text, next click will deselect the text and so on.


Here is one way to do it from this post also a question here as well.

If you want to select/deselect you can simply adjust your click handler to the following:

<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);
    }
});

Example of it on jsfiddle.


I did like this:

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)
      } 
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜