gpt4 book ai didi

javascript - 居中元素?

转载 作者:太空宇宙 更新时间:2023-11-03 21:01:09 25 4
gpt4 key购买 nike

如果我有一行链接,例如:

 <a>foobar</a><a>foobar</a><a>foobar</a><a id="center">foobar</a><a>foobar</a>

但是其中一个有一个 id="center",我可以用 javascript 或 css 将它定位在中心吗?

最佳答案

如果您指的是 DOM 局部性...

您可能必须通过脚本实际操作 DOM。我的猜测是您需要有一种方法来通过容器或通用类名来引用所有这些链接。然后将链接总数除以 2,在该特定索引处插入中心链接。

$(function(){
var bodyLinks = $("body a");
var halfPoint = Math.floor(Number(bodyLinks.length/2)-1);
$("body a:eq("+halfPoint+")").after($("#center"));
});​

在线演示:http://jsbin.com/aroba/edit

如果您指的是 CSS 放置:

<p><!-- padleft -->link1 link2 link3 **link4** link5 link6                               link1 **link2** link3 link4 link5 link6       link1 link2 link3 link4 link5 **link6**

This solution is a bit premature, and could benefit from some further development. Essentially I placed the links within a paragraph. I then calculated the total width of all elements preceding the special-link (our center link) and used it to figure a padding-left for the containing paragraph tag.

$(function(){
var elWidth = $("#center").width();
var elOffset = $("#center").offset().left;
var wnWidth = $("body").width();
var sibWidths = 0;

$("#center").prevAll("a").each(function(){
sibWidths = sibWidths + $(this).width();
});

var gutter = ((wnWidth-elWidth)/2)-sibWidths;

$("body p:first").css({paddingLeft:gutter});

});

在线演示:http://jsbin.com/oniba/edit

关于javascript - 居中元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2230336/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com