简体   繁体   中英

Change the width div after pressing li or if # in the URL

I've written a code that sets the width for the.line when you press the selected li. I also want, if url contains #first to give.line the width of element#first. Why doesn't this code work. Please help me.

var set = document.querySelectorAll('li');
var line = document.querySelector('.line');

if(window.location.hash == "#first"){
  lineScale(document.querySelector('#first'));
};

for(i=0;i<set.length;i++)set[i].addEventListener('click',lineScale(el));
function lineScale(el){
  line.style.transform = 'scaleX(' + el.getBoundingClientRect().width + ')';
};
<ul>
  <li><a href="#first" id="first">First</a></li>
  <li><a href="#second" id="second">Second</a></li>
  <li><a href="#third" id="third">Third</a></li>
  <li><a href="#fourth" id="fourth">Fourth</a></li>
  <span class="line"></span>
</ul>
li {
  display: inline-block;
}
.line {
  display: block;
  width: 1px;
  height: 2px;
  transform-origin: left;
  background-color: #000;
}

There are at least two issues with your event listener for click.

One is that you are trying to include an argument in the adding of the event. This is preventing your event handler from being called (since the handler is lineScale , not lineScale(el) ). Secondly, the first argument to the event handler is not the element but an event. You can use this in the event handler to reference the element that the event is occurring for.

Thus:

for(i = 0; i < set.length; i++)
  set[i].addEventListener('click', lineScale);

function lineScale(){
  line.style.transform = 'scaleX(' + this.getBoundingClientRect().width + ')';
};

When debugging your javascript, make use of the developer's console in your browser. It will show you errors that occur in the javascript. For example, when you have .addEventListener('click', lineScale(el)); the developer's console in Chrome shows:

Uncaught ReferenceError: el is not defined

That's because, as it says, el is not defined in that context. After fixing that issue, when you tried to reference the el argument as an element, this error shows up in the developer's console:

Uncaught TypeError: el.getBoundingClientRect is not a function
    at HTMLLIElement.lineScale 

You probably have other issues preventing you from achieving your ultimate goal, but this should get you much further without solving all of the individual problems. Additional problems should be posted as a separate question if you are having trouble with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM