pointer-events в CSS


css ‘pointer-events’ property alternative for IE

I have a drop down navigation menu in which some of the title should not navigate to other page when clicked(these title open a drop down menu when clicked on) while others should navigate (these dont have dropdown and navigate directly).However, both types have href defined to them

To solve this i added the following css for the former type of titles

and it is working fine.But since this property is not supported by IE, i am looking for some work-around. The annoying thing is that i don’t have access and privilege to change the HTML and JavaScript code completely.

12 Answers 12

Pointer-events is a Mozilla hack and where it has been implemented in Webkit browsers, you can’t expect to see it in IE browsers for another million years.

There is however a solution I found:

This uses a plugin that uses some not well known/understood properties of Javascript to take the mouse event and send it to another element.

There is also another Javascript solution here.

Update for October 2013: apparently it’s coming to IE in v11. Source. Thanks Tim.

Here is another solution that is very easy to implement with 5 lines of code:

  1. Capture the ‘mousedown’ event for the top element (the element you want to turn off pointer events).
  2. In the ‘mousedown’ hide the top element.
  3. Use ‘document.elementFromPoint()’ to get the underlying element.
  4. Unhide the top element.
  5. Execute the desired event for the underlying element.


There’s a workaround for IE — use inline SVG and set pointer-events=»none» in SVG. See my answer in How to make Internet Explorer emulate pointer-events:none?

It’s worth mentioning that specifically for IE, disabled=disabled works for anchor tags:

IE treats this as an disabled element and does not trigger click event. However, disabled is not a valid attribute on an anchor tag. Hence this won’t work in other browsers. For them pointer-events:none is required in the styling.

UPDATE 1: So adding following rule feels like a cross-browser solution to me

UPDATE 2: For further compatibility, because IE will not form styles for anchor tags with disabled=’disabled’ , so they will still look active. Thus, a:hover<> rule and styling is a good idea:

Working on Chrome, IE11, and IE8.
Of course, above CSS assumes anchor tags are rendered with disabled=»disabled»

Использование css-свойства pointer-events

Это может показаться удивительным, но существует css-атрибут pointer-events, который позволяет, например, выключить все события, которые можно вызвать на элементе нажатием мышки (или пальцем):

Да, отключить обработку событий при помощи css. Поддерживается всеми нормальными браузерами. Один из примеров использования: есть оверлэй поверх все страницы, и всё ещё хочется что бы элементы под оверлеем реагировали на нажатия как будто оверлея нет. На сайте MDM очень хорошо расписаны различные значения и особенности использования pointer-events.

Мы рассказываем, как стать более лучшим разработчиком, как поддерживать и эффективно применять свои навыки. Информация о вакансиях и акциях эксклюзивно для более чем 8000 подписчиков. Присоединяйся!

  • mkdev

  • Менторы
  • Специализации
  • Статьи
  • О проекте
  • Что такое менторство
  • Как проходит обучение
  • Цены
  • FAQ
  • Impressum


  • Аккаунт
  • Записаться
  • Войти
  • Соцсети

© Copyright 2014 — 2020 mkdev | Privacy Policy | Lang: Russian

Илон Маск рекомендует:  Что такое код asp logextfilecookie

Свойство pointer-events в css

Это свойство определяет может ли мышь взаимодействовать с элементом.

По умолчанию стоит значение auto.


Значение none предотвращает события: hover, active, click и прочие. При чём не только в css но и в js.

Не работает в старых IE, доступно только начиная с IE11.

Зачем?

1. Чтобы элемент не реагировал на наведение мыши, если в css прописаны стили для :hover и прочих.

2. Чтобы отключить правую кнопку мыши.

3. Для ускорения скроллинга, т. к. без hover перерисовок станет меньше.

pointer-events

The pointer-events property is used to control under what conditions particular graphic elements can become the target of pointer events.

Please note that is an SVG property and is not defined in any CSS specification.

The pointer-events property can have many values that are applicable to SVG elements, but only three of these values are applicable to HTML elements.

When pointer-events is used on HTML elements, it can specify whether or not an element can respond to mouse (or touch) events. It can be used to prevent click, state (CSS active, focus, and hover states), and cursor actions (showing the pointer cursor over links, for example).

You can either have the element respond to pointer events ( auto ), or prevent it from doing so ( none ). If you prevent the it from responding to pointer events, an element that is underneath it will become the target of these events. If you click the element, the element beneath it will receive that click event. Same applies to hover and other cursor actions. For example, you would be able to select text in an element that is positioned beneath an element with pointer-events: none (see demo below).

The pointer-events property can be very useful in different scenarios. One advantage of this property is allowing you to create 60fps scrolling by using pointer-events: none . Ryan Seddon has written a detailed article on how it works; his article is worth a read.


Trivia & Notes

Disabling pointer events on an element can be overridden on a child element: If a child of the element has pointer-events: auto (i.e. enabled), it will be able to handle and respond to click events, even if its parent doesn’t.

As mentioned above, the pointer-events property is an SVG property. Despite being present in the early drafts of the User Interface Module Level 3, it was removed from that module and pushed to Level 4. More about that here.

Official Syntax

  • Syntax: Formal Syntax:

The values in the official syntax are applicable to SVG elements. Of these values, only these are applicable to HTML:

  • Initial: auto
  • Applies To: all elements
  • Animatable: no

  • Values

    Notes

    See the SVG specification for more information about the remaining values.

    Examples

    The following example positions an overlay element over the entire page. The overlay would be faded into view via some JavaScript method that would be fired if the user performs some kind of action on the page, for example. In order to prevent the overlay from blocking pointer events on the rest of the elements on the page, we’re going to disable pointer events on it, so that the events can be fired on the page beneath it as they normally would.

    Then, using JavaScript, the element could be faded into view, and the pointer events can be enabled on it so that the user can interact with it as needed.

    Live Demo

    In the following example, the overlay has pointer-events: none , so you can select the text and click the anchor tags beneath it. Also notice how the cursor turns into a pointer (pointing hand) when you hover over the links, because the hover states are fired on them.

    Илон Маск рекомендует:  Iis веб и ftp узлы

    Try changing the none value to auto to see how it makes the overlay prevent pointer events from being fired on the links and anything beneath it.

    Browser Support


    CSS pointer-events (for HTML)

    This CSS property, when set to «none» allows elements to not receive hover/click events, instead the event will occur on anything behind it.

    Pointer Events

    Class Properties
    .pointer-events-none pointer-events: none;
    .pointer-events-auto pointer-events: auto;

    Usage

    Use .pointer-events-auto to revert to the default browser behavior for pointer events (like :hover and click ).

    Use .pointer-events-none to make an element ignore pointer events. The pointer events will still trigger on child elements and pass-through to elements that are «beneath» the target.

    Try clicking the caret icon to open the dropdown

    .pointer-events-auto (event captured)

    .pointer-events-none (event passes through)

    pointer-events

    Easily manage projects with monday.com


    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.

    While the pointer-events property takes eleven possible values, all but three of them are reserved for use with SVG. The three valid values for any HTMl element are:

    • 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 behaviour 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.

    Points of Interest

    • “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.” — Dav >

    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


    Chrome Opera Firefox IE Edge Safari
    4 15 3.6 11 12 4

    Mobile / Tablet

    iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
    3.2 46 No 2.1 78 68

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

    CSS pointer-events

    The responsibilities taken on by CSS seems to be increasingly blurring with JavaScript. Consider the -webkit-touch-callout CSS property, which prevents iOS’s link dialog menu when you tap and hold a clickable element. The pointer-events property is even more JavaScript-like, preventing:

    • click actions from doing anything
    • the default cursor pointer from displaying
    • CSS hover and active state triggering
    • JavaScript click events from firing

    One CSS property is capable of doing just that!

    The CSS

    The pointer-events property can have many values, but many of them are only applicable to SVG*: auto , none , visiblePainted* , visibleFill* , visibleStroke* , visible* , painted* , fill* , stroke* , all* , and inherit . The none value prevents the click, state, and cursor actions:

    A few quick notes about pointer-events :

    • If children of the element have pointer-events explicitly enabled, clicks will be allowed on those child elements.
    • 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.

    I first noticed pointer-events used on the Firefox Marketplace website for disabled buttons. A bonus in this case is styleability; think about how awful elements with the disabled attribute look! Of course, don’t use pointer-events on elements that could trigger critical functionality — the style can simply be remove via the console!

    Pointer-events: none; cursor: default

    Идея такова, берем блок, для него pointer-events: none;
    Дальше через jQuery создаем блок, который будет крепиться за курсором [Только в случае, если курсор над блоком с pointer-events: none;] (с отступом слева и сверху для клика), для этого блока делаем cursor: pointer например. Дальше у нас получаеться, по идее что будет зона где можно кликнуть, а курсор с блоком под ним будет иметь нужную нам форму.

    Слой 2 — pointer-events: none;
    Слой 1 — cursor: pointer; С зазором. А так, сам искал на стэк оверфлоу. Говорят, такое невозможно сделать. Можете тогда более точно описать задачу?

    One more step

    Please complete the security check to access codepen.io

    Why do I have to complete a CAPTCHA?

    Completing the CAPTCHA proves you are a human and gives you temporary access to the web property.

    What can I do to prevent this in the future?

    If you are on a personal connection, like at home, you can run an anti-virus scan on your device to make sure it is not infected with malware.

    If you are at an office or shared network, you can ask the network administrator to run a scan across the network looking for misconfigured or infected devices.

    Another way to prevent getting this page in the future is to use Privacy Pass. You may need to download version 2.0 now from the Chrome Web Store.

    Cloudflare Ray ID: 534072a90c468e5f • Your IP : 188.64.174.135 • Performance & security by Cloudflare

    Pointer-events в CSS

    Создание базовых элементов HTML, доступных для клика, используя CSS-свойство pointer-events. Когда мы помещаем элемент HTML над другим элементом, то базовый элемент становится не кликабельным. Мы можем сделать элемент top верхним для обхода событий мыши, это клик, наведение и так далее. И все это на базовом элементе, где задействовано свойство CSS pointer-events.

    По умолчанию значение указателя-события является автоматическим для всех элементов, поэтому верхний элемент блокирует события мыши для базовых элементов. Делая события-указатели равными «none», мы можем заставить верхние элементы передавать события мыши нижележащим элементам.

    .box1
    <
    height: 100px;
    width: 100px;
    background-color: yellow;
    >

    .box2
    <
    height: 100px;
    width: 100px;
    background-color: green;
    pointer-events: none;
    >

    Свойство pointer-events позволяет управлять над тем, как HTML элементы реагируют на мышь или сенсорные события, в том числе активное состояний.

    Демонстрация Страна: (RU)

    Дата: Четверг, 2020-05-30, 04:04 | Сообщение 2

    Хотя pointer-events свойство принимает одиннадцать возможных значений, все кроме трех, зарезервированы для использования с SVG. Когда pointer-events используется на элементах HTML, он может указывать, может ли элемент реагировать на события мыши.

    none запрещает все параметры щелчка, состояния и курсора для указанного элемента HTML.
    auto восстанавливает функциональность по умолчанию, что полезно для использования на дочерних элементах элемента с указанным pointer-events: none; свойством.
    inherit будет использовать pointer-events значение родительского элемента.

    Илон Маск рекомендует:  Write писать в файл
    Понравилась статья? Поделиться с друзьями:
    Кодинг, CSS и SQL