想要点击按钮点击页面顶部,目前我使用以下代码无效:
HTML:
<button md-raised-button class="md-raised md-primary" (click)="onEdit()">Edit</button>
Run Code Online (Sandbox Code Playgroud)
功能:
onEdit(){
window.scrollTo(0,0);
}
Run Code Online (Sandbox Code Playgroud)
onEdit(){
document.body.scrollTop = document.documentElement.scrollTop = 0;
}
Run Code Online (Sandbox Code Playgroud)
这是我的解决方案,部分基于w3schools的后退按钮示例。
的HTML:
<button (click)="topFunction()" id="myBtn" title="Go to top">Top</button>
Run Code Online (Sandbox Code Playgroud)
CSS:
/*-----------------------------Button-------------------*/
#myBtn {
display: none; /* Hidden by default */
position: fixed; /* Fixed/sticky position */
bottom: 20px; /* Place the button at the bottom of the page */
right: 30px; /* Place the button 30px from the right */
z-index: 99; /* Make sure it does not overlap */
border: none; /* Remove borders */
outline: none; /* Remove outline */
background-color: red; /* Set a background color */
color: white; /* Text color */
cursor: pointer; /* Add a mouse pointer on hover */
padding: 15px; /* Some padding */
border-radius: 10px; /* Rounded corners */
font-size: 18px; /* Increase font size */
}
#myBtn:hover {
background-color: #555; /* Add a dark-grey background on hover */
}
Run Code Online (Sandbox Code Playgroud)
打字稿:
@HostListener("window:scroll", []) onWindowScroll() {
this.scrollFunction();
}
// When the user scrolls down 20px from the top of the document, show the button
scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("myBtn").style.display = "block";
} else {
document.getElementById("myBtn").style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
topFunction() {
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
Run Code Online (Sandbox Code Playgroud)
希望它能帮助任何人
正确的方法是使用DOCUMENT DI 代币
导入它
import { Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
Run Code Online (Sandbox Code Playgroud)
注入文档
constructor(@Inject(DOCUMENT) private dom: Document) {
}
Run Code Online (Sandbox Code Playgroud)
然后你可以打电话
this.dom.body.scrollTop =0;
this.dom.documentElement.scrollTop=0;
Run Code Online (Sandbox Code Playgroud)
这也适用于 SSR(Angular Universal)
| 归档时间: |
|
| 查看次数: |
14258 次 |
| 最近记录: |