检查CSS标题属性(如果它不为空并添加内容) [英] Checking CSS title attribute if it's not empty and add content

查看:147
本文介绍了检查CSS标题属性(如果它不为空并添加内容)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是:检查title属性是否为空;如果不是那么应该添加此标题属性的值加一个连字符。



这是我当前的CSS代码:

  div:hover :: before {content:attr(title):not(attr(title)=) - ;} 

但不能按预期工作。



例如:

 < div title =My username>一些文字< / div> 

应悬浮显示以下内容:



< >

我的用户名 - 一些文本


但如果:


$ b b

 < div title =>一些文字< / div> 

或(div上没有标题):

 < div>一些文字< / div> 

则悬停时的显示应为:



< blockquote>

一些文本


是否可以修复?


<你可以使用属性选择器和 attr()函数来完成这个任务。 attr()函数只是获取给定属性的值 - 它不支持任何条件语句本身。



注意,我使用 [title =] :not([title])标题属性以及缺少标题属性。你可以通过在你的第一个规则中包含 [title] 来省略:not() t工作在互联网对不起,我的意思是它不工作在 Chrome



  div:hover: :before {content:attr(title) - ;} div [title =]:hover :: before,div:not([title]):hover :: before {content:none;}  

 < div title =My username> some text< / div ;< div title =>一些文本< / div>< div>一些文本< / div>  

p>

My goal is to: check if the title attribute is not empty; if it is not then there should be added the value of this title attribute plus a hyphen. On the other hand, if the title attribute is empty then the " - " should not be added at all.

Here is my current CSS code:

div:hover::before{content:attr(title):not(attr(title)="") " - ";}

but it doesn’t work as expected.

For example:

<div title="My username">some text</div>

should display the following on hover:

My username - some text

But if:

<div title="">some text</div>

or (no title on div):

<div>some text</div>

then the display on hover should be:

some text

Is it possible to fix it?

解决方案

You can use attribute selectors in conjunction with the attr() function to accomplish this. The attr() function simply grabs the value of a given attribute — it does not support any conditional statements itself.

Notice that I use [title=""] and :not([title]) to account for both empty title attributes as well as the lack of a title attribute altogether. You could omit the :not() part by including [title] in your first rule instead, but that doesn't work in Internet E— sorry, I meant it doesn't work in Chrome.

div:hover::before {
    content: attr(title) " - ";
}

div[title=""]:hover::before, div:not([title]):hover::before {
    content: none;
}

<div title="My username">some text</div>
<div title="">some text</div>
<div>some text</div>

这篇关于检查CSS标题属性(如果它不为空并添加内容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆