CSS or JS max. character <h2> and replace end with "..."
I assume my title basically summed it all up.
I have a <h2>
title, and I want it to have a max character property, be it CSS or javascript, so that whenever this maximum limit is passed, the title's end is replaced by ... (three dots).
Thank you very much in advance.
An example can be viewed here: http://themeforest.net/forums/thread/now-accepting-bargain-submissions/23205 (see the tit开发者_StackOverflow社区le)P.S. Any idea why I had to create a new user? the login-feature through google doesn't recognize my previous user :(
Pure javascript style
var maxLen = 30;
var titles = document.getElementsByTagName("h2");
for(i in titles){
if(titles[i].innerHTML.length > maxLen){
titles[i].innerHTML = titles[i].innerHTML.substr(0, maxLen)+"...";
}
}
Doing this by CSS you could set width for h2
with overflow: hidden
If using a hellip is not necessary, you can consider this pure-css solution:
h2 {
max-width: 300px;
white-space: nowrap;
overflow: hidden;
}
h2:before {
content: " "; /* unicode space Alt+255 */
display: block;
background: url(shadow.png) top right repeat-y;
height: 100%;
width: 20px;
float: right;
position: relative;
}
shadow.png is small horizontal gradient from transparency to your background color. Unfortunately, there is some problem in IE.
You can do it with CSS by specifying a fixed width for H2 elements, or with JavaScript:
function shorten(el, maxlength) {
for (i = 0; i < el.length; i++) {
if (el[i].innerText.length > maxlength) {
el[i].innerHTML = el[i].innerText.substr(0, maxlength) + "…";
}
}
}
window.onload = function() {
shorten(document.getElementsByTagName('h2'), 20);
}
精彩评论