function StringBuffer() {
this._strings = [];
}
StringBuffer.prototype.append = function(str) {
this._strings.push(str);
return this; // 鏈式調用
};
StringBuffer.prototype.toString = function() {
return this._strings.join('');
};
// 使用
var buf = new StringBuffer();
buf.append("Hello ").append("World");
console.log(buf.toString()); // "Hello World"
現代 JS 引擎(V8、SpiderMonkey)已優化字符串拼接,通常直接用+或模板字符串\`\`即可,無需此模式。
// 文檔總尺寸
function pageHeight() { return document.body.scrollHeight; }
function pageWidth() { return document.body.scrollWidth; }
// 滾動條位置
function scrollX() {
var de = document.documentElement;
return window.pageXOffset || (de && de.scrollLeft) || document.body.scrollLeft;
}
function scrollY() {
var de = document.documentElement;
return window.pageYOffset || (de && de.scrollTop) || document.body.scrollTop;
}
// 視口尺寸
function windowHeight() {
var de = document.documentElement;
return window.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
}
function windowWidth() {
var de = document.documentElement;
return window.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
}
現代瀏覽器直接用 window.innerWidth、document.documentElement.clientWidth、window.scrollX/Y。
function setOpacity(elem, level) { // level: 0-100
if (elem.filters) { // IE 8-
elem.style.filter = 'alpha(opacity=' + level + ')';
} else {
elem.style.opacity = level / 100;
}
}
// 頁面座標
function getPageX(e) { e = e || window.event; return e.pageX || e.clientX + document.body.scrollLeft; }
function getPageY(e) { e = e || window.event; return e.pageY || e.clientY + document.body.scrollTop; }
// 元素內部座標
function getElementX(e) { return (e && e.layerX) || window.event.offsetX; }
function getElementY(e) { return (e && e.layerY) || window.event.offsetY; }
function hide(elem) {
var cur = getStyle(elem, 'display');
if (cur !== 'none') elem._oldDisplay = cur;
elem.style.display = 'none';
}
function show(elem) {
elem.style.display = elem._oldDisplay || '';
}
// 依賴 getStyle(見下)
function getStyle(elem, prop) {
// 1. 內聯樣式
if (elem.style[prop]) return elem.style[prop];
// 2. IE currentStyle
if (elem.currentStyle) return elem.currentStyle[prop];
// 3. W3C getComputedStyle
if (document.defaultView && document.defaultView.getComputedStyle) {
var cssProp = prop.replace(/([A-Z])/g, '-$1').toLowerCase();
var style = document.defaultView.getComputedStyle(elem, '');
return style && style.getPropertyValue(cssProp);
}
return null;
}
function getHeight(elem) { return parseInt(getStyle(elem, 'height')) || elem.offsetHeight; }
function getWidth(elem) { return parseInt(getStyle(elem, 'width')) || elem.offsetWidth; }
現代開發建議:
• 尺寸用elem.getBoundingClientRect()(含 transform 縮放後真實尺寸)。
• 樣式用window.getComputedStyle(el)。
• 滾動用window.scrollX/Y、element.scrollTop/Left。
• 透明度直接用opacity(IE9+)。