简体   繁体   中英

How do I select and unselect multiple elements with JavaScript or jQuery?

I am working currently on some online editor and I would like to have there the posibility to select multiple elements (all this same class) while holding ctrl key - just like in most of the programs and then make some actions on them - eg. align.

The second thing what I want to achive is to be able to deselect all when I click somewhere - if on element then all beside this, if outside all elements then all elements.

I was trying to insert them into a table if they are clicked and then perform some action - only on objects from this table, but then I don't know how to make them be select only with ctrl button if there is any.

I have also tried this function on clicking outside objects:

$('html').click(function(){
    alert("Deselect");
})

But it does't work either.

So, does anyone know any other way to perform this actions?

And here is an example of what I would like to achive (you have to click Advanced Editing ) - I mean the align list in the right top corner of editor. Also there is deselection of object when you press outside one, and ctrl selection.

http://www.vistaprint.com

Thank you for your help and ideas.

I suggest you to use the Event delegation : You attach a click event handler on some container that works as follows:

  1. If ctrl button is not pressed, clear all selections (Maybe you keep all selected items in some list — just remove them all).
  2. If click happen on some element that can be selected (you can determine what element was clicked via event.target, see an article mentioned above) select that one (add to a list).

About ctrl button: You need a keydown and keyup event handlers. In one of them you turn some isCtrlPressed variable to true , in another — to false .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM