Это опубликовано по двум простым причинам:
- Я прокомментировал и сказал, что вам нужно использовать 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 .
Примечания: эта функция не будет работать в тех браузерах, таких как IE, которые не имеют реализации window.getComputedStyle()
.Это, вероятно, гарантирует, что, как бы ни было интересно, этот скрипт вряд ли будет использоваться.За исключением, возможно, в измененной форме (я, конечно, свободно даю этот сценарий любому, кто захочет его использовать, выпуская его даже за пределами CC-By-SA лицензии Stack Overflow, так как я думаю я могу ...).Хотя, если кто-то и изменит его, я буду искренне признателен за ссылку на измененную версию, либо в комментариях, либо путем редактирования этого ответа для добавления ссылок ...
Ссылки: