Как мне установить активное состояние для кнопок изображения вместо просто сфокусированного состояния с моим текущим кодом? - PullRequest
0 голосов
/ 03 апреля 2020

Первая публикация здесь и новшество в программировании с опытом работы всего 3 дня.
У меня возникают проблемы с получением кнопки по умолчанию active вместо focused. Я пытался прочитать другие посты об этом, но из-за недостатка опыта мне сложно соединить 2 и 2.

Страница переходит в квадратное пространство, поэтому я пытаюсь сделать все это в одном блоке кода. Я не хочу, чтобы кнопки отключались, когда пользователь нажимает на другие части веб-сайта, что в настоящее время происходит. (Даже если они нажимают на пустые области).

Большое спасибо за любой совет, который вы можете дать мне.

/* Change Button Size/Border/BG Color And Align To Middle */

.services {
  width: 210px;
  height: 135px;
  padding: 0px;
  border: 0px;
  outline: 0px;
  cursor: pointer;
  color: #999999;
  font-size: 20px;
  text-align: center;
  background: url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat;
  /* As all link share the same background-image */
}


/* Set Mouseover Button Text and Current/Active Color */

.services:focus,
.services:hover,
.services:active {
  color: black;
}


/* Position Button Text*/

divtext {
  position: relative;
  top: 90px;
}


/* Div Wrapper to format button areas. */

.servicesbuttonwrapper {
  display: flex;
  flex-flow: row wrap;
  justify-content: space-around;
}


/* Div Wrapper to format revealed description text. */

.servicestextwrapper {
  text-align: left;
  margin-left: 100px;
  margin-right: 32px;
  top: 50px;
  position: relative;
}


/* Change Image rollover position depending On Focus. */

.assets {
  background-position: 0 0;
}

.assets:focus,
.assets:hover,
.assets:active {
  background-position: 0 -135px;
}

.viz {
  background-position: 0 -270px;
}

.viz:focus,
.viz:hover,
.viz:active {
  background-position: 0 -405px;
}

.software {
  background-position: 0 -540px;
}

.software:focus,
.software:hover,
.software:active {
  background-position: 0 -675px;
}

.more {
  background-position: 0 -810px;
}

.more:focus,
.more:hover,
.more:active {
  background-position: 0 -945px;
}


/* Hides intitial button descriptions. */

#assets,
#viz,
#software,
#more {
  display: none;
}
<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Services</title>
</head>

<body>

  <!--Div wrapper so we can format positioning of buttons in CSS-->
  <div class="servicesbuttonwrapper">

    <!--Base buttons plus javascript functions for click behavior.  This used to be <button class> instead of <a href> but I read somewhere this is better...  seems to work ok.-->

    <a href="javascript:void(0)" id="defaultstate" onclick="show('software');" class="services software">
      <divtext>INTERACTIVE SOFTWARE</divtext>
    </a>

    <a href="javascript:void(0)" onclick="show('assets');" class="services assets">
      <divtext>3D ASSET CREATION</divtext>
    </a>

    <a href="javascript:void(0)" onclick="show('viz');" class="services viz">
      <divtext>3D VISUALIZATION</divtext>
    </a>

    <a href="javascript:void(0)" onclick="show('more');" class="services more">
      <divtext>IMAGE CREATION</divtext>
    </a>
  </div>

  <!--Base description text.-->
  <div class="servicestextwrapper">
    <div id="assets">3D Assets Description.</div>
    <div id="viz">3D Visualization Description.</div>
    <div id="software">Interactive Software Description.</div>
    <div id="more">And More Description.</div>
  </div>

  <!--Javascript function to hide/show elements based on button press.-->
  <script type="text/javascript">
    function show(elementId) {
      document.getElementById("assets").style.display = "none";
      document.getElementById("viz").style.display = "none";
      document.getElementById("software").style.display = "none";
      document.getElementById("more").style.display = "none";
      document.getElementById(elementId).style.display = "block";
    }
  </script>

  <!--Javascript function to set first button as focus.-->
  <script>
    window.onload = function() {
      document.getElementById("defaultstate").click();
    };
    var linkToFocus = document.getElementById('defaultstate');
    linkToFocus.focus();
  </script>

</body>

</html>

1 Ответ

0 голосов
/ 03 апреля 2020

Добро пожаловать в переполнение стека.

Итак, первое, что нужно отметить, псевдоэлемент: active применяется только тогда, когда пользователь нажимает на кнопку мыши. Вы можете увидеть это здесь

Самый распространенный метод - применить класс css «активный» и использовать селектор .active для любого элемента, который вы хотите стилизовать.

Прямо сейчас у вас есть кнопки, на которые влияют наведение и фокусировка, поэтому, когда пользователь нажимает за пределами кнопки, он теряет фокус.

Вы можете решить эту проблему, изменив бит CSS и javascript. Отредактированные части помечены /* EDIT */

Я бы не рекомендовал в последней строке использовать тот факт, что ваша функция передает идентификатор элемента, а этот идентификатор элемента соответствует классу кнопки, которая использовалась для выберите его. Лучшим способом было бы show принять событие Javascript в качестве аргумента, затем использовать event.target, чтобы щелкнуть тег, затем использовать getElementById для чего-то вроде атрибута data-target="more". Это позволит вам изменить класс CSS без привязки класса к реализации Javascript

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Services</title>
</head>

<style>/* Change Button Size/Border/BG Color And Align To Middle */

    .services {
        width:210px;
        height:135px;
        padding: 0px;
        border:0px;
        outline:0px;
        cursor: pointer;
        color: #999999;
        font-size: 20px;
        text-align: center;
		background:   url("https://i.ibb.co/G5mn9nY/Services-Buttons-Combined-Big.png") no-repeat; /* As all link share the same background-image */
    }

    
/* Set Mouseover Button Text and Current/Active Color */
/* EDIT */
    .services:focus, .services:hover, .services.active {
        color: black;
    }
    

/* Position Button Text*/
	divtext {
    position: relative;
    top: 90px;
    }
    
/* Div Wrapper to format button areas. */ 
.servicesbuttonwrapper {
    display: flex;
    flex-flow: row wrap;
    justify-content: space-around;
   }

/* Div Wrapper to format revealed description text. */ 
.servicestextwrapper {
    text-align: left;
    margin-left: 100px;
    margin-right: 32px;
    top: 50px;
    position: relative;
}


/* Change Image rollover position depending On Focus. */
    .assets      {
        background-position: 0 0;
    }
    
    /* EDIT */
    .assets:focus, .assets:hover, .assets.active  {
        background-position: 0 -135px;
    }
    
    
    .viz        {
        background-position: 0 -270px;
    }
    
    /* EDIT */
    .viz:focus, .viz:hover, .viz.active  {
        background-position: 0 -405px;
    }
        
    
    .software   {
        background-position: 0 -540px;
    }
    
    /* EDIT */
    .software:focus, .software:hover, .software.active  {
        background-position: 0 -675px;
    }
    
    .more       {
        background-position: 0 -810px;
    }
    
    /* EDIT */
    .more:focus, .more:hover, .more.active  {
        background-position: 0 -945px;
    }


/* Hides intitial button descriptions. */
#assets, #viz, #software, #more {
    display: none;
} 


</style>

<body>
   
<!--Div wrapper so we can format positioning of buttons in CSS-->
	<div class="servicesbuttonwrapper">

<!--Base buttons plus javascript functions for click behavior.  This used to be <button class> instead of <a href> but I read somewhere this is better...  seems to work ok.--> 

    	<a href="javascript:void(0)" id="defaultstate" onclick="show('software');" class="services software"><divtext>INTERACTIVE SOFTWARE</divtext></a>
           
   		<a href="javascript:void(0)" onclick="show('assets');" class="services assets"><divtext>3D ASSET CREATION</divtext></a>
                
		<a href="javascript:void(0)" onclick="show('viz');" class="services viz"><divtext>3D VISUALIZATION</divtext></a>
                
		<a href="javascript:void(0)" onclick="show('more');" class="services more"><divtext>IMAGE CREATION</divtext></a>
   </div>
   
<!--Base description text.--> 
   <div class="servicestextwrapper">
        <div id="assets">3D Assets Description.</div>
		<div id="viz">3D Visualization Description.</div>
		<div id="software">Interactive Software Description.</div>
		<div id="more">And More Description.</div>
   </div>   
   
<!--Javascript function to hide/show elements based on button press.--> 
<script type="text/javascript">
    /* EDIT */
    function show(elementId) {
        document.getElementById("assets").style.display = "none";
        document.getElementById("viz").style.display = "none";
        document.getElementById("software").style.display = "none";
		document.getElementById("more").style.display = "none";
        document.getElementById(elementId).style.display = "block";
        
        // get a list of the buttons with ".services" class
        const buttons = document.querySelectorAll(".services");
        
        for(let button of buttons) {
          // remove ".active" class
          button.classList.remove("active");
        }
        
        // add the active class to element button specified by argument
        document.querySelector("." + elementId).classList.add("active");
    }  
   </script>
   
<!--Javascript function to set first button as focus.--> 
<script>
window.onload=function(){
  document.getElementById("defaultstate").click();
};
var linkToFocus = document.getElementById('defaultstate');
linkToFocus.focus();

</script>

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...