//样式模拟 div > div { width: 200px; height: 500px; border: 1px solid #38c46d; } #anchor { position: fixed; width: 100px; height: 200px; border: 1px solid #000; right: 16px; top: calc(50% - 50px); padding: 0; :deep(li) { width: 100%; text-align: center; list-style: none; a { color: #000; } } } //元素模拟 <div id="area"> <div id="box1">box1</div> <div id="box2">box2</div> <div id="box3">box3</div> </div> <div> <ul id="anchor"></ul> </div> //js控制动态生成锚点
//思路:遍历某个区域内所有的拥有id的子元素,然后生成锚点集;exclude代表特殊情况,排除某些元素,使其不生成锚点;
//具体样式自己调整,加setTimeout是因为在vue或者react中,为了保证元素节点已生成。 /** * * @param area 统计某个区域的id * @param id 在某个元素上生成锚点集 * @param exclude 排除某个元素锚点 */ const createAnchor = (area: string, id: string, exclude?: Array<string>) => { setTimeout(() => { let areaDoc = document.getElementById(area); let anchorDoc = document.getElementById(id); let str = ""; areaDoc.childNodes.forEach((value: any, index) => { if (value.id) { if (exclude) { if (exclude.indexOf(value.id) < 0) { str += `<li><a href='#${value.id}' title='${value.textContent}'>${value.textContent}</a></li>`; } } else { str += `<li><a href='#${value.id}' title='${value.textContent}'>${value.textContent}</a></li>`; } } }); anchorDoc.innerHTML = str; }, 0); }; createAnchor("area", "anchor");
标签:area,悬浮,value,锚点,str,exclude,右侧,id From: https://www.cnblogs.com/xinyouhunran/p/17463811.html