CSS仅在div有文本时才添加指针样式



在以下情况下,如何将cursor:pointer仅添加到包含文本Cursor pointer required here的第二个div中。

具有class="x95qze"div保持不变。使用javascript添加/删除其中的divtext

只有当div class="x95qze内有纯文本时,才需要cursor:pointer

<!DOCTYPE html>
<html>
<head>
<title>Cursor</title>
</head>
<body>
<div class="x95qze">
<div class="RiYDI">No cursor pointer required here</div>
</div>

<div class="x95qze">Cursor pointer required here.</div>
</body>
</html>

CSS:

.x95qze {
border:1px solid black;
padding:5px;
}

.x95qze .RiYDI {
border:1px solid black;
width:50%
}

试试这个:

HTML

<div class="x95qze"><span id="js-output">Cursor pointer required here.</span></div>

CSS

#js-output {
cursor:pointer;
display:inline-block;
}

如果您知道文本,则可以使用纯javascriptincludes

首先查找文本

const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
// expected output: "The word "fox" is in the sentence"
if (sentence.includes(word)) {
let element = document.querySelector('.x95qze);
element.setAttribute("style", "cursor:pointer;");
}

更多信息MDN

Jquery有一个名为:contains(text)的文本选择器。更新内容后,我调用一个函数,该函数迭代.x95qze类标签,并将cursored类添加到没有子标签的标签中。

cursored类的css中,我添加了cursor:pointer规则。

function checkCursors(){
$('.x95qze:contains(Cursor)').each(function(i, container) {
$(container).toggleClass('cursored',   $(container).children().length == 0);
});
}
// After content updated
checkCursors();
.x95qze.cursored { cursor:pointer; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Cursor</title>
</head>
<body>
<div class="x95qze">
<div class="RiYDI">No cursor pointer required here</div>
</div>

<div class="x95qze">Cursor pointer required here.</div>
</body>
</html>

最新更新