Как сделать функцию JavaScript работать только на рабочем столе - PullRequest
0 голосов
/ 15 марта 2020

Я создал функцию JavaScript, которая показывает подчеркивание под каждым именем меню, но я хочу, чтобы эта функция работала ТОЛЬКО на рабочем столе.

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

 function myFunction(x) {
  if (x.matches) { // If media query matches
    document.body.style.backgroundColor = "yellow";
  } else {
    document.body.style.backgroundColor = "pink";
  }
}

var x = window.matchMedia("(max-width: 700px)")
myFunction(x) // Call listener function at run time
x.addListener(myFunction) // Attach listener function on state changes

Вот оригинальный код До того, как я использовал код, показанный выше.

(function() {

  const target = document.querySelector(".target");
  const links = document.querySelectorAll(".mynav a");
  const colors = ["deepskyblue", "orange", "firebrick", "gold", "magenta", "black", "darkblue"];

  function mouseenterFunc() {
    if (!this.parentNode.classList.contains("active")) {
      for (let i = 0; i < links.length; i++) {
        if (links[i].parentNode.classList.contains("active")) {
          links[i].parentNode.classList.remove("active");
        }
        links[i].style.opacity = "0.25";
      }

      this.parentNode.classList.add("active");
      this.style.opacity = "1";

      const width = this.getBoundingClientRect().width;
      const height = this.getBoundingClientRect().height;
      const left = this.getBoundingClientRect().left + window.pageXOffset;
      const top = this.getBoundingClientRect().top + window.pageYOffset;
      const color = colors[Math.floor(Math.random() * colors.length)];

      target.style.width = `${width}px`;
      target.style.height = `${height}px`;
      target.style.left = `${left}px`;
      target.style.top = `${top}px`;
      target.style.borderColor = color;
      target.style.transform = "none";
    }
  }

  for (let i = 0; i < links.length; i++) {
    links[i].addEventListener("click", (e) => e.preventDefault());
    links[i].addEventListener("mouseenter", mouseenterFunc);
  }

  function resizeFunc() {
    const active = document.querySelector(" .mynav li.active");

    if (active) {
      const left = active.getBoundingClientRect().left + window.pageXOffset;
      const top = active.getBoundingClientRect().top + window.pageYOffset;

      target.style.left = `${left}px`;
      target.style.top = `${top}px`;
    }
  }

  window.addEventListener("resize", resizeFunc);
  
  
// Event Listener To Remove Line From Floating in Air When Leaving Dropdown Box - START

document.querySelector(".mynav").addEventListener("mouseleave", function() {
  target.removeAttribute("style");
})
  
// Event Listener To Remove Line From Floating in Air When Leaving Dropdown Box - END


})();


/* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */
function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
      x.className += " responsive";
    } else {
      x.className = "topnav";
    }
  }
@import url('https://fonts.googleapis.com/css?family=Roboto:400,500,700,900&display=swap');


/* 
YELLOW - #f7c51e
GREY - #363636
background white - #f6f6f6

*/



* {
    box-sizing: border-box;
    margin: 0; 
    padding: 0;
}


.color-overlay-container {
    justify-content: center;
    align-items: center;
    position: relative;
}

.color-overlay {
    width: 100%;
    height: 100%;
    background: #000;
    opacity: .5;
    z-index: 2;
    position: absolute;
}


.btn-black{
    padding: 1.5rem 2rem;
    color: white;
    background: black;
    text-transform: uppercase;
    font-weight: 900;
}

.btn-yellow{
    padding: 1.5rem 2rem;
    color:  white;
    background: #f7c51e;
    text-transform: uppercase;
    font-weight: 900;
}


body {
    font-family: 'Roboto', sans-serif;
    line-height: 1.4;
}

a {
    text-decoration: none;
}


p {
    margin: .5rem 0;
}

/* Utility Classes */

/* Grid Container */


.grid-container {
display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 1rem;
  margin: auto;
  grid-auto-rows: minmax(200px, auto);
}

.grid-container-2 {
    display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 1rem;
  margin: auto;
}

.card {
    background: #fff;
    padding: 1rem;
}


/* Grid Container - END */


.container {
    max-width: 1404px;
    margin: auto;
    padding: 0 2rem;
    overflow: hidden;
}


.text-center {
    text-align: center;
}


.text-yellow {
    color: #f7c51e;
}

.bg-yellow {
    background: #f7c51e;
    color: black;
}

.bg-grey {
    background: #f9f9f9;
    color: black;
}


.l-heading {
    font-weight: bold;
    font-size: 4rem;
    margin-bottom: 0.75rem;
    line-height: 1.1;
}

.m-heading {
    font-size: 2rem;
    margin-bottom: 0.75rem;
    line-height: 1.1;
}

.lead {
    font-size: 1.3rem;
    margin: 0.75rem 0;
}



/* Padding */

.py-1 {
    padding: 1.5rem 0;
}

.py-2 {
    padding: 2rem 0;
}

.py-3 {
    padding: 3rem 0;
}


/* All Around Padding */

.p-1 {
    padding: 1.5rem;
}

.p-2 {
    padding: 2rem;
}

.p-3 {
    padding: 3rem;
}


/* Utility Classes - END */



/* ================  HOME PAGE ==================== */


/* HEADER */



.site-header {
    background-color: transparent;
}

.site-header .header-container {
    background: black;
    color: white;
}

/* BLACK BAR */

.site-header .header-container .header-container_wrap {
    padding: 30px 5px;
    /* background: red; */
}

#masthead .header-container .header-container_wrap .items {
    display: flex;

}

#masthead .header-container .header-container_wrap .items .contact-info {
    display: flex;

}

#masthead .header-container .header-container_wrap .items .quality-logo {
    margin-right: 3rem;
    line-height: 5px;
}

#masthead .header-container .header-container_wrap .items .quality-logo p {
    font-size: 14px;
}


#masthead .header-container .header-container_wrap .items .item {
    display: flex;
    align-items: center;
    margin-right: 1rem;
}


#masthead .header-container .header-container_wrap .items .item {
    display: flex;
    align-items: center;
    margin-right: 1rem;
}

#masthead .header-container .header-container_wrap .items .item .facebook-like {
    text-align: center;
}



#masthead .header-container .header-container_wrap .items .item .fas  {
    font-size: 18px;
    color: #f7c51e;
    margin-right: 1.5rem;
}


#masthead .header-container .header-container_wrap .items .contact-info .item .fas  {
    font-size: 18px;
    color: #f7c51e;
    margin-right: 1.5rem;
    background: black;
    border-radius: 50%;
    padding: 10px;
    border: 1px solid #363636;
}

/* ========================== Bottom White Header Menu  - START ================ */


/* Menu Underline */


.mynav a {
    display: block;
    font-size: 20px;
    color: black;
    text-decoration: none;
    padding: 7px 15px;
  }
  
  .target {
    position: absolute;
    border-bottom: 4px solid transparent;
    z-index: 100;
    transform: translateX(-60px);
    pointer-events: none;
  }
  
  .mynav a,
  .target {
    transition: all .35s ease-in-out;
  }



/* Add a black background color to the top navigation */
.topnav {
    background-color: white;
    overflow: hidden;
    padding: 1rem;

  }


  #myTopnav .items {
      display: flex;
      justify-content: space-between;
      align-items: center;
  }
  

  #myTopnav .items .item .mynav ul{
      display: flex;
      align-items: center;
  }
  

  #myTopnav .items .item .mynav ul li{
      display: flex;
      align-items: center;
  }
  

  #myTopnav .items .item .mynav ul li:nth-child(4){
      margin-left: .5rem;
      /* background-color: red; */
  }
  
  /* Style the links inside the navigation bar */
  .topnav a {
    /* float: left;
    display: block; */
    color: rgb(94,94,94);
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    font-size: 17px;
    text-transform: uppercase;
    font-weight: 600;
  }
  
  /* Add an active class to highlight the current page */

/*     
    .active {
     color: black;
    font-weight: 600; 
    color: #363636;
   }  */
  

  /* Hide the link that should open and close the topnav on small screens */
  .topnav .icon {
    display: none;
  }
  

  /* ============================ DROP DOWN MENU =============================== */
  /* Dropdown container - needed to position the dropdown content */
  .dropdown {
    /* float: left; */
    overflow: hidden;
  }
  
  /* Style the dropdown button to fit inside the topnav */
  .dropdown .dropbtn {
    font-size: 17px;
    border: none;
    outline: none;
    color: rgb(94,94,94);
    padding: 14px 16px;
    background-color: inherit;
    font-family: inherit;
    margin: 0;
    text-transform: uppercase;
    font-weight: 600;
    display: flex;
    align-items: center;
  }
  
  /* Style the dropdown content (hidden by default) */
  .dropdown-content {
    display: none;
    position: absolute;
    background-color: #f7c51e;
    min-width: 160px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    z-index: 1;
    color: rgb(94,94,94);
  }
  
  /* Style the links inside the dropdown */
.mynav   .dropdown-content a {
    font-size: 14px;
    font-weight: 500;
    float: none;
    color: white;
    padding: 12px 16px;
    text-decoration: none;
    display: block;
    text-align: left;
    text-transform: uppercase;
  }
  
  /* Add a dark background on topnav links and the dropdown button on hover */
  .topnav a:hover, .dropdown:hover .dropbtn {
    /* background-color: red; */
    color: black;
    

  }
  
  /* Add a grey background to dropdown links on hover */
  .dropdown-content a:hover {
    /* background-color: red; */
    color: black;
    
  }

  
  /* Show the dropdown menu when the user moves the mouse over the dropdown button */
  .dropdown:hover .dropdown-content {
    display: block;
    z-index: 101;
  }
  
  
  /* SEARCH ICONS */

  #myTopnav .items .item .fa-search{
      font-size: 1.25rem;
      color: #363636;
  }




/* ========================== Bottom White Header Menu - END ================ */





  
  @media screen and (max-width: 600px) {


   /*  ================== Top Black Bar ============= */


   /* ================ WHITE MENU NAVBAR DROPDOWN - START ============ */

   .topnav  {
      display: flex;
      justify-content: center;
      
   }

   .topnav .hamburger {
      display: flex;
      align-items: center;
      
   }
   
   .topnav a, .dropdown .dropbtn {
      display: none;
    }


    .topnav a p {
      margin-right: 1rem;
    }
    .topnav a.icon {
      display: flex;
      align-items: center;
    }



   .topnav.responsive {position: relative;}

   .topnav.responsive {
      display: flex;
      align-items: center;
   }
/*    
   .topnav.responsive .icon {
     position: absolute;
     right: 0;
     top: 0;
   } */

   .topnav .items .item {
      display: flex;
      flex-direction: column;
  }

   .topnav.responsive .container .items .item {
      display: flex;
      flex-direction: column;
  }

/* AFTER YOU CLICK ON HAMBURGER */

.topnav.responsive .container .items .item  a {
   float: none;
   display: block;
   text-align: left;
}


.topnav.responsive a.icon {
   display: flex !important;
   align-items: center;
}

.topnav.responsive .dropdown {float: none;}
.topnav.responsive .dropdown-content {position: relative;}
.topnav.responsive .dropdown .dropbtn {
   display: block;
   width: 100%;
   /* text-align: left; */
}





   /* ================ WHITE MENU NAVBAR DROPDOWN - END ============ */





   #masthead .header-container .header-container_wrap .items .quality-logo {
      margin: auto;
      margin-bottom: 1rem;
   }


   #masthead .header-container .header-container_wrap .items .quality-logo p {
      font-size: 10px;
  }

  #masthead .header-container .header-container_wrap .items .contact-info {
   display: flex;
   flex-direction: column;
}

  #masthead .header-container .header-container_wrap  {
   padding: 2rem;
}

  #masthead .header-container .header-container_wrap .items .item {
   margin-bottom: .5rem;
   margin-right: 0;
}



  #masthead .header-container .header-container_wrap .items .item .contact-block__value-wrap  {
   margin-bottom: 0rem;
}

  #masthead .header-container .header-container_wrap .items .item .contact-block__value-wrap p {
   line-height: .75rem;
}

/* White Menu Bar */

#masthead .header-container .fixed-nav {
   margin-top: -40px;
}

/* Facebook */

#masthead .header-container .header-container_wrap .items .item .facebook-like {
   text-align: center;
   /* align-self: center; */
   margin: auto;
}

.l-heading {
   font-weight: bold;
   font-size: 2rem;
   margin-bottom: 0.75rem;
   line-height: 1.1;
}


.m-heading {
   font-weight: bold;
   font-size: 1rem;
   margin-bottom: 0.75rem;
   line-height: 1.1;
}

.swiper-button-next:after, .swiper-container-rtl .swiper-button-prev:after, .swiper-button-prev:after, .swiper-container-rtl .swiper-button-next:after {
   font-size: 2rem;
}



  }
image

Ответы [ 3 ]

0 голосов
/ 15 марта 2020

JS

Самым простым решением, которое я вижу для вашей проблемы, является проверка, является ли значение JS window.innerWidth большим или равным 992px (минимальная ширина рабочего стола).

CSS

Однако, так как вы действительно хотите применить стилизацию, связанную с CSS, вы, скорее всего, захотите написать медиа-запрос для своей работы.

Пример:

@media screen and (min-width: 992px) {
    /* CSS-styling for desktop */
}

Лучше всего разместить их внизу таблицы стилей CSS. Если вы не знакомы с ними, я настоятельно рекомендую проверить их.

0 голосов
/ 15 марта 2020

Извините, ребята, я понял ответ, и это было легко исправить. Вместо добавления другой функции javascript я просто использовал приведенный ниже код в CSS Media Query для мобильных устройств.

@media screen and (max-width: 600px) {
    /* Removing the Menu Underline For Ipad and Mobile */

    .target {
       display: none;
    }

}
0 голосов
/ 15 марта 2020

Вы можете попробовать это. Надеюсь, это сработает.

//User agent for Mobile only...
if(navigator.userAgent.match(/Mobile|Windows Phone|Lumia|Android|webOS|iPhone|iPod|Blackberry|PlayBook|BB10|Opera Mini|\bCrMo\/|Opera Mobi/i) ) {
    console.log('Mobile Stuff...');
}

//User agent for Tablet only...
if (navigator.userAgent.match(/Tablet|iPad/i)) {
    console.log('Tablet Stuff...');
}

//User-agent for Desktop only...
if(!navigator.userAgent.match(/Mobile|Windows Phone|Lumia|Android|webOS|iPhone|iPod|Blackberry|PlayBook|BB10|Opera Mini|\bCrMo\/|Opera Mobi|Tablet|iPad/i) ) {
    console.log('Desktop Stuff...');
}
...