<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { margin: 0; padding: 0; list-style: none; } html, body { width: 100%; height: 100%; } ul { width: 100%; height: auto; } li { height: 35px; display: flex; align-items: center; } </style> </head> <body> <div class="box"> <div class="goBottom">点击回到底部</div> <div class="cont"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> <li>11</li> <li>12</li> <li>13</li> <li>14</li> <li class="showLi">在这里显示</li> <li>15</li> <li>16</li> <li>17</li> <li>18</li> <li>19</li> <li>20</li> <li>21</li> <li>22</li> <li>23</li> <li>24</li> <li>25</li> <li>26</li> <li>27</li> <li>28</li> <li>29</li> <li>30</li> <li>31</li> <li>32</li> <li>33</li> <li>34</li> <li>35</li> <li>36</li> <li>37</li> <li>38</li> <li>39</li> <li>40</li> <li>41</li> <li>42</li> <li>43</li> <li>44</li> <li>45</li> <li>46</li> <li>47</li> <li>48</li> <li>49</li> <li>50</li> </ul> </div> <div class="goTop">点击回到顶部</div> <div class="goShowView">到指定区域</div> </div> </body> <script> var goTop = document.querySelector('.goTop') var goBottom = document.querySelector('.goBottom') // 1.平滑回到页面最顶部 goTop.addEventListener('click', function () { window.scrollTo({ top: 0, left: 0, behavior: "smooth" }); }) // 2.平滑的到页面最底部 goBottom.addEventListener('click', function () { console.log(document.documentElement.offsetHeight); window.scrollTo({ top: document.documentElement.offsetHeight, left: 0, behavior: "smooth", }); }) // 3.将元素滚动到可见区域 const goShowView = document.querySelector(".goShowView"); const showLi = document.querySelector(".showLi"); const smoothScroll = (element) => { element.scrollIntoView({ behavior: "smooth", }); }; goShowView.addEventListener("click", () => { smoothScroll(showLi); }); </script> </html> |