首页 > 解决方案 > 使用 window.location 设置样式

问题描述

所以我有这个项目我正在处理,我试图根据身份验证状态隐藏/显示一些元素。我设法让所有其他元素按我的意愿工作,但我有一个特定元素的问题。我有一个上传表单,我只想在用户登录时显示它。这是我的表单:

<form id="addVideo" class="uploadForm">
        <h3>Alege fisier:</h3>
        <input id="fileUpload" type="file" required>
        <input id="caption" type="text" required>            
        <button id="buttonSubmit" onclick="uploadFile()">Submit </button>
</form>

这是我的 JS:

const btnLogin = document.getElementById('modalBtn');
const btnLogout = document.getElementById('logout');
const contentUploader = document.getElementById('addVideo');
const btnAcasa = document.getElementById('acasa');
const btnBiblioteca = document.getElementById('biblioteca'); 

const setUI = (user)=>{
if(user){
btnLogin.style.display='none';
btnLogout.style.display='block';
if(window.location == 'biblioteca.html'){
  contentUploader.style.display ='block'; 
}     
btnAcasa.style.display='block';
btnBiblioteca.style.display ='block'; 
}
else{
btnLogin.style.display = 'block';
btnLogout.style.display = 'none';
if(window.location === 'biblioteca.html'){
  contentUploader.style.display = 'none'; 
}    
btnAcasa.style.display ='block';
btnBiblioteca.style.display ='block'; 
}

我正在使用 window.location 因为我在 2 个不同的页面上运行这个脚本。这是我调用函数的方式:

auth.onAuthStateChanged(user =>{
if(user){
  setUI(user);    
  console.log(user);
}
else{
setUI()    
console.log(user);
}
})

标签: javascripthtmlcsswindow.location

解决方案


Window.location返回 Location 对象,该对象不等于字符串。参考https://developer.mozilla.org/en-US/docs/Web/API/Window/location

你可以使用

if(window.location.href == 'biblioteca.html'){
  contentUploader.style.display ='block'; 
}

但是在这里您还需要考虑域名和之前的所有内容biblioteca.html


推荐阅读