选择具有CSS属性cursor:pointer的dom

问题描述 投票:-2回答:2
<div class="classname">some test<div>
<style> div.classname{cursor:pointer}</style>

我要选择上面的CSS示例分配了光标指针的dom

不确定类似下面的内容

document.querySelector('[cursor=pointer]')
jquery css jquery-selectors
2个回答
1
投票

我们可以使用

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

但是这仅适用于inline样式,这些样式是我们直接使用style属性在元素上设置的,如下所示:

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

要根据计算样式(在这种情况下,使用类)查找dom元素,我们将需要遍历页面上的所有元素,然后使用getComputedStyle()方法像:

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
}

0
投票

我想出了以下解决方案

<div class="classname">some test
<div>
© www.soinside.com 2019 - 2024. All rights reserved.