выберите домен с css курсором свойства: указатель - PullRequest
0 голосов
/ 09 апреля 2020
<div class="classname">some test<div>
<style> div.classname{cursor:pointer}</style>

Я хочу выбрать dom, для которого указатель курсора назначен CSS пример выше

не уверен, что-то вроде ниже

document.querySelector('[cursor=pointer]')

Ответы [ 2 ]

1 голос
/ 09 апреля 2020

Мы можем использовать

document.querySelector('[style*="cursor:pointer"]')

, но это работает только для встроенных стилей, которые мы устанавливаем для элементов напрямую, используя атрибут style, например:

const elem = document.querySelector('[style*="cursor:pointer"]')
console.log( elem )
<div class="classname" style="cursor:pointer">some test<div>

Чтобы найти элемент dom на основе вычисленного стиля (как в этом случае с использованием класса ) нам потребуется l oop через все элементы на странице и затем использовать метод getComputedStyle(), например:

(function() {
  // Get all elements on the page
  let elms = [...document.querySelectorAll('*')];
  
  // loop through all elements and getComputedStyle 
  elms.some(el => {
    let compStyles = window.getComputedStyle(el);
    
    // Find the cursor property of current dom element
    if (compStyles.getPropertyValue('cursor') == 'pointer') {
      console.log('Element found')
      console.log(el)
      return true; // break the loop here
    }
  });
})();
div.classname {
  cursor: pointer
}
<div class="classname">some test
<div>
0 голосов
/ 09 апреля 2020

я придумал решение ниже

function getCursorPointerDomArray()
{
    let ar=[];
    let dom=document;
    function iterateDomNode(dom)
    {
        let c,noIterate=false;
        try{   
            c=getComputedStyle(dom);
            if(c.getPropertyValue('cursor')=='pointer')
            {
                ar.push(dom);         
                noIterate=true;
            }
        }catch(e)
        {

        }
        if(dom.hasChildNodes() && noIterate==false)
        {
            for(let i=0;i<dom.childNodes.length;i++)
            {
                iterateDomNode(dom.childNodes[i]);
            }
        }        
    }   
    iterateDomNode(dom) 
    return ar;
}
...