发布此内容有两个简单的原因:
- 我评论说你需要使用 JavaScript,并且
- 有时候,我就是忍不住...
也就是说,这是一个不需要任何库的纯 JavaScript 解决方案。有点繁琐,感觉一定有办法可以简化,不过:
// helper function, to save typing later on.
function gEBTN(tag, parent, index) {
if (!parent && !index) {
return document.getElementsByTagName(tag);
}
else if (parent && !index) {
return parent.getElementsByTagName(tag);
}
else if (index) {
return parent.getElementsByTagName(tag)[index];
}
}
// helper function, to save typing later on.
function gCS(elem, parent, prop) {
if (!prop && parent) {
return window.getComputedStyle(elem.parentNode, null).getPropertyValue('width');
}
else if (prop && parent == true) {
return window.getComputedStyle(elem.parentNode, null).getPropertyValue(prop);
}
else if (!parent && !prop) {
return window.getComputedStyle(elem, null).getPropertyValue('width');
}
else {
return window.getComputedStyle(elem, null).getPropertyValue(prop);
}
}
// page: number.
// navElemId: a quoted string, the Id of the element containing
// the navigation elements, defaults to 'navigation'
// container: a quoted string, the type of element ('div','span','li'...)
// that forms the navigation 'buttons.' Defaults to 'li.'
function centreNavigationOn(page, navElemId, container) {
if (!page) { // at minimum you have to supply the page you want to centre on
return false;
}
else {
var navElemId = navElemId || 'navigation';
var navElem = document.getElementById(navElemId);
var containers = gEBTN(container) || gEBTN('li', navElem);
for (var i = 0, len = containers.length; i < len; i++) {
if (containers[i].innerHTML == page) {
var centreOn = containers[i];
}
else {
// just for an easy visual difference between the centred/current
// page and the others. Adjust/remove according to taste
containers[i].style.opacity = '0.3';
}
}
if (!centreOn){
// if no page is found to be centred on, quits
console.log('No element found to centre on. Quitting now.');
return false;
}
// again, just for simple visual difference between current and others...
centreOn.style.backgroundColor = '#f90';
centreOn.style.opacity = '1';
// finds the width of the centreOn element
var cOnWidth = parseInt(gCS(centreOn),10);
var cOnLeftOffset = centreOn.offsetLeft;
// the centreOn element's parent's parent's width
// this made sense when I wrote it, now...I'm not so sure... =/
cPPWidth = parseInt(gCS(centreOn.parentNode.parentNode),10);
// works out by what distance the centreOn element's parent
// must be moved in order to centre the centreOn element within the page.
var moveBy = Math.round((cPPWidth/2) - (cOnLeftOffset + (cOnWidth/2)));
centreOn.parentNode.style.marginLeft = moveBy + 'px';
}
};
centreNavigationOn(4, 'navigation', 'li');
JS Fiddle demo.
注意事项:在没有window.getComputedStyle() 实现的浏览器(如IE)中,此功能会失效。这可能保证了,尽管组合起来很有趣,但这个脚本不太可能被使用。除了,也许,以修改后的形式(当然,我愿意将此脚本免费提供给任何想要使用它的人,甚至在 Stack Overflow 的 CC-By-SA license 之外发布它,正如我认为 '能够...)。虽然如果有人修改它,我真的很感激他们链接到修改后的版本,无论是在 cmets 中还是通过编辑这个答案来添加链接......
参考资料: