官术网_书友最值得收藏!

Attribute selectors

Attribute selectors are a particularly helpful subset of CSS selectors. They allow us to specify an element by one of its HTML attributes, such as a link's title attribute or an image's alt attribute. For example, to select all images that have an alt attribute, we write the following:

$('img[alt]')

Styling links

Attribute selectors accept a wildcard syntax inspired by regular expressions for identifying the value at the beginning (^) or end ($) of a string. They can also take an asterisk (*) to indicate the value at an arbitrary position within a string or an exclamation mark (!) to indicate a negated value.

Let's say we want to have different styles for different types of links. We first define the styles in our stylesheet:

a {
  color: #00c; 
}
a.mailto {
  background: url(images/email.png) no-repeat right top;
  padding-right: 18px;
}
a.pdflink {
  background: url(images/pdf.png) no-repeat right top;
  padding-right: 18px;
}
a.henrylink {
  background-color: #fff;
  padding: 2px;
  border: 1px solid #000;
}

Then, we add the three classes—mailto, pdflink, and henrylink—to the appropriate links using jQuery.

To add a class for all e-mail links, we construct a selector that looks for all anchor elements (a) with an href attribute ([href]) that begins with mailto: (^="mailto:"), as follows:

$(document).ready(function() {
  $('a[href^="mailto:"]').addClass('mailto');
});

Listing 2.3

Because of the rules defined in the page's stylesheet, an envelope image appears after the mailto: link on the page.

To add a class for all the links to PDF files, we use the dollar sign rather than the caret symbol. This is because we're selecting links with an href attribute that ends with .pdf:

$(document).ready(function() {
  $('a[href^="mailto:"]').addClass('mailto');
 $('a[href$=".pdf"]').addClass('pdflink');
});

Listing 2.4

The stylesheet rule for the newly added pdflink class causes an Adobe Acrobat icon to appear after each link to a PDF document, as shown in the following screenshot:

Attribute selectors can be combined as well. We can, for example, add the class henrylink to all links with an href value that both starts with http and contains henry anywhere:

$(document).ready(function() {
  $('a[href^="mailto:"]').addClass('mailto');
  $('a[href$=".pdf"]').addClass('pdflink');
 $('a[href^="http"][href*="henry"]')
 .addClass('henrylink');
  });
});

Listing 2.5

With the three classes applied to the three types of links, we should see the following:

Note the PDF icon to the right-hand side of the Hamlet link, the envelope icon next to the email link, and the white background and black border around the Henry V link.

主站蜘蛛池模板: 崇仁县| 南漳县| 临泉县| 定兴县| 启东市| 津市市| 苗栗县| 扬州市| 涟源市| 固安县| 望都县| 台南市| 土默特左旗| 津南区| 阿城市| 定南县| 常德市| 瑞安市| 高青县| 廊坊市| 高雄县| 社旗县| 建昌县| 游戏| 略阳县| 贵定县| 兴山县| 朝阳市| 台中市| 绵阳市| 乐业县| 文成县| 博罗县| 石楼县| 武宣县| 班玛县| 夏邑县| 房产| 濮阳县| 南郑县| 泽州县|