No click mouse css

pointer-events

The pointer-events property allows for control over how HTML elements respond to mouse/touch events – including CSS hover/active states, click/tap events in Javascript, and whether or not the cursor is visible.

  • none prevents all click, state and cursor options on the specified HTML element
  • auto restores the default functionality (useful for use on child elements of an element with pointer-events: none; specified
  • inherit will use the pointer-events value of the element’s parent

As demonstrated above, the prime use case for pointer-events is to allow click or tap behavior to “pass through” an element to another element below it on the Z axis. For example, this would be useful for graphic overlays, or hiding elements with opacity (eg. tooltips) and still allowing text-selection on the content below it.

  • “The use of pointer-events in CSS for non-SVG elements is experimental. The feature used to be part of the CSS3 UI draft specification but, due to many open issues, has been postponed to CSS4.” — Mozilla MDN
  • “If you add a click event listener to an element, then remove the pointer-events style (or change its value to auto, the click event will fire the designated functionality. Basically, the click event respects the pointer-events value.” — David Walsh

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop

Mobile / Tablet

The support is a bit deeper in some browsers when used on , for instance, IE 9 supports that.

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

@deepak – “what’s a right click?” –Mac users for 20 years. Right-clicking is a mouse action, but not a pointer-event. The HTML api for the DOM doesn’t define an “onrightclick” event and there is no native listener for the event. The closest match for handling right clicking is the newer context menu api for the popup menu, but this is not directly a result of right clicking, as any keyboard key or interactive device can be set to open the context menu.

@Tony – brush up on your JS knowledge. Right click is natively handled via onclick where event.button == 2 – see https://developer.mozilla.org/en-US/docs/Web/Reference/Events/click . And don’t brag about being a Mac user for 20 years, it’s like you’re asking for sarcasm 😉

Remember you already can edit de text on inputs by pressing Tab key and… just typing =D. You must have to disable states on form elements and set readonly=”readonly”…

It works, but note that; inside an element where pointer-events have been set to none , for IE11 to take notice of a pointer-events: auto , the target element must also have a CSS position other than static :

pointer-events: auto; position: relative;

Superb! Really need more time to experiment with SVG and this seems like a way better solution than mitigating event bubbles in JavaScript. I’ve noticed which Canvas you register click events on the container of a circle, but with SVG the circle is almost like a clipMask (or Mask in Flash). I’ve attempted to use clipMask in SVG and place the foreignObject inside of the clipMask only to discover that clipMask doesn’t accept the foreignObject. Does anyone have any ideas how you would add circular objects that rotate in a circle, inside of SVG where whatever is behind the outer edge of the circle is not registered as an event by the SVG above it? Think of like a rotary telephone with a switch on the side or something.

Читайте также:  Javascript return variable value

This will certainly be a handy way of allowing events to “pass through” elements, and for temporarily disabling pseudo states. But I’m struggling to see how it’s of much use for anything else. How, for example, would you implement drag and drop using pointer events, without also blocking scale and zoom gestures? It doesn’t appear to be possible. Microsoft’s suggestion is to set “touch-action” to either “pan-x” or “pan-y” — e.g. if it’s set to “pan-y” then vertical swiping scrolls the page, while horizontal swiping fires events you can use for drag and drop. So the drag action would only work if you did it horizontally. That might be acceptable for applications, where page scaling is disabled, but it’s of no use on web pages, where the scaling might be large enough that the page scrolls in both directions. And I don’t think it’s particular intuitive either way. Pointer events might be a useful high-level abstraction, but they’re no substitute for proper low-level touch events.

hmmm, not what I expected…in this example it does not appear that it passes events to elements below the stacking order, nor z-index, as this article suggests so this is useless of you have a full viewport overlay and wish to interact with elements below (underneath) it. Am I reading this wrong? http://codepen.io/pingram3541/pen/hvtFH (try clicking on div.two “through” div.four) it doesn’t work nor does it show the hover state for the anchor. Example has both an inherit anchor as well as js event handler.

I take that last post back, partially…I can’t believe I did this as I almost never use IE except for testing for the stuff it breaks…but sure enough I was using IE when I built the codepen lol. The css rule works on webkit. =)

lol, wish I could edit my comments so as not to pollute this thread… Found a solution for IE, but it isn’t perfect…since the WC3 spec is for svg, if the overlay is defined as an svg, pointer-events are in fact passed through. And a possible js solution – http://www.vinylfox.com/forwarding-mouse-events-through-layers/

This line of CSS is great – can cancel links without touching PHP :
“pointer-events: none;” I have used it to cancel top level link menu in WP.
IF it affects also sub menus then put “pointer-events: auto;” on the sub menu CSS. Works great.

Actually, it works on fixed elements. I have a fixed user bar with some icons in it (links to login and such). As a responsive layout the menu collapses into a fixed menu bar (transparent background) which is stacked above the user bar. The icons in the user were no longer accessible. By using pointer-events:none on the menu bar and pointer-events:auto on the menu items, everything works as expected, even through fixed elements.

Читайте также:  Timing loops in python

THIS JUST SAVED MY LIFE. I was doing an overlay over a gallery, where I would display a magnifying glass on hover. The problem is that the overlay layer was taking precedence over the anchor, and the Foundation Clearing gallery I was using relies on what is clicked to identify the gallery content. pointer-events:none on the overlay div and it was all solved. 😀

I’d much rather there be separate properties for “click-events” and “hover-events” so I could control them separately. After all a “pointer” isn’t even an event, lol. I guess touch-events could be broken into swipe-events and tap-events as well, but I’ve not found a use case for that, yet.

Источник

pointer-events

CSS-свойство pointer-events позволяет контролировать события, при которых элемент может стать объектом события мыши. Если это свойство не задано, то к содержимому SVG будут применяться характеристики значения visiblePainted.

Вдобавок к указанию того, что элемент не является объектом события мыши, значение none сообщает событию мыши проходить «через» элемент и обращаться к элементу, находящемуся «под» ним.

Начальное значение auto
Применяется к все элементы
Наследуется да
Обработка значения как указано
Animation type discrete

Синтаксис

/* Значения ключевых слов */ pointer-events: auto; pointer-events: none; pointer-events: visiblePainted; /* только SVG */ pointer-events: visibleFill; /* только SVG */ pointer-events: visibleStroke; /* только SVG */ pointer-events: visible; /* только SVG */ pointer-events: painted; /* только SVG */ pointer-events: fill; /* только SVG */ pointer-events: stroke; /* только SVG */ pointer-events: all; /* только SVG */ /* Глобальные значения */ pointer-events: inherit; pointer-events: initial; pointer-events: unset; 

Значения

Элемент ведёт себя так же, как и если бы свойство pointer-events не было задано. В SVG это значение даёт такой же эффект, как и значение visiblePainted .

Элемент не может быть целью (target) событий мыши; тем не менее, целью событий мыши могут быть его потомки, если их pointer-events имеет какое-либо другое значение. В этом случае события мыши вызовут ожидаемое срабатывание обработчиков на этом родительском элементе на пути к/от потомк(у)/(а) во время фазы захвата/всплытия .

Только SVG. Элемент может быть целью события мыши только когда свойство visibility установлено в значение visible и когда курсор мыши находится над внутренней частью (‘fill’) элемента, при этом свойство fill установлено в значение отличное от none , или над периметром элемента (‘stroke’), при этом свойство stroke установлено в значение отличное от none .

Только SVG. Элемент может быть целью события мыши только когда свойство visibility установлено в значение visible и когда курсор мыши находится над внутренней частью (‘fill’) элемента. Значение свойства fill не влияет на обработку события.

Только SVG. Элемент может быть целью события мыши только когда свойство visibility установлено в значение visible и когда курсор мыши находится над периметром элемента (‘stroke’). Значение свойства stroke не влияет на обработку события.

Читайте также:  Таблицы

Только SVG. Элемент может быть целью события мыши только когда свойство visibility установлено в значение visible и когда курсор мыши находится над внутренней частью (‘fill’) или над периметром (‘stroke’) элемента. Значение свойств fill и stroke не влияют на обработку события.

Только SVG. Элемент может быть целью события мыши только когда курсор мыши находится над внутренней частью (‘fill’) элемента, при этом свойство fill установлено в значение отличное от none , или над периметром элемента (‘stroke’), при этом свойство stroke установлено в значение отличное от none . Значение свойства visibility не влияет на обработку события.

Только SVG. Элемент может быть целью события мыши только когда курсор мыши находится над внутренней частью (‘fill’) элемента. Значение свойств visibility и fill не влияют на обработку события.

Только SVG. Элемент может быть целью события мыши только когда курсор мыши находится над периметром элемента (‘stroke’). Значение свойств visibility и stroke не влияют на обработку события.

Только SVG. Элемент может быть целью события мыши только когда курсор мыши находится над внутренней частью (‘fill’) или над периметром (‘stroke’) элемента. Значение свойств visibility , fill и stroke не влияют на обработку события.

Формальный синтаксис

pointer-events =
auto | (en-US)
bounding-box | (en-US)
visiblePainted | (en-US)
visibleFill | (en-US)
visibleStroke | (en-US)
visible | (en-US)
painted | (en-US)
fill | (en-US)
stroke | (en-US)
all | (en-US)
none

Примеры

Пример 1

/* Пример 1: Сделать так, что бы все объекты img не реагировали на перетаскивание, наведение(:hover), нажатие(click) и т.д. */ img  pointer-events: none; > 

Пример 2

Сделать ссылку на ресурс http://example.com не реагирующей на нажатие(click), наведение(:hover) и т.д.

ul> li>a href="https://developer.mozilla.org">MDNa>li> li>a href="http://example.com">example.coma>li> ul> 
a[href="http://example.com"]  pointer-events: none; > 

Примечание

Обратите внимание, что предотвращение того, чтобы элемент был объектом событий мыши, с помощью pointer-events не обязательно означает, что обработчики событий мыши на этом элементе не могут или не будут запускаться. Если у одного из дочерних элементов есть явные pointer-events, позволяющие этому ребёнку быть объектом событий мыши, тогда любые события, нацеленные на этого дочернего элемента, будут проходить через родителя, когда событие перемещается вдоль родительской цепочки и запускает обработчики событий на родительском объекте. Конечно, любая активность мыши в точке на экране, которая покрывается родителем, но не дочерним, не будет поймана ни ребёнком, ни родителем (он пройдёт через «родительский» на «цели» под ним).

Мы хотели бы предоставить более тонкий контроль (а не только auto и none ) в HTML, когда части элемента смогут «поймать» события мыши. Если у вас есть какие-то конкретные вещи, чтобы помочь нам в решении как следует расширить pointer-events для HTML, и которые вы хотели бы сделать с этим свойством, добавьте их в раздел «Использовать случаи» на этой странице вики (не беспокойтесь, мы всё сохраним аккуратно).

Характеристики

Это расширение для элементов HTML, хоть и присутствует в ранних версиях CSS Basic User Module Interface Level 3, было перенесено на level 4.

Совместимость браузера

BCD tables only load in the browser

Смотрите также

Found a content problem with this page?

This page was last modified on 30 нояб. 2022 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью