简体   繁体   中英

how can I change this html code to javascript?

I'm new to Javascript and our teacher only allows us to use Javascript although most of the examples and answers to my questions are written in html.

I want to make a dropdown button which contains various links.

The example online says:

</style>
</head>
<body>

<div class="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <div class="dropdown">
  <button class="dropbtn" onclick="myFunction()">Dropdown
    <i class="fa fa-caret-down"></i>
  </button>
  <div class="dropdown-content" id="myDropdown">
    <a href="#">Link 1</a>
    <a href="#">Link 2</a>
    <a href="#">Link 3</a>
  </div>
  </div> 
</div>

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

// Close the dropdown if the user clicks outside of it
window.onclick = function(e) {
  if (!e.target.matches('.dropbtn')) {
  var myDropdown = document.getElementById("myDropdown");
    if (myDropdown.classList.contains('show')) {
      myDropdown.classList.remove('show');
    }
  }
}

so in an attempt to translate this all to Javascript only I wrote

var navbar = document.createElement("div");
navbar.className = "navbar";
document.body.append(navbar);

var colorButton = document.createElement("a");
colorButton.innerText = "color";
navbar.append(colorButton);

var genreButton = document.createElement("a");
genreButton.innerText = "genre";
navbar.append(genreButton);

var dropdown = document.createElement("div");
dropdown.className = "dropdown";
dropdown.id = "dropdown";
navbar.append(dropdown);

var dropbtn = document.createElement("BUTTON");
dropbtn.className = "dropbtn";
dropbtn.innerHTML = "dropDown";
navbar.appendChild(dropbtn);

var idk = document.createElement("i");
idk.className = "fa fa-caret-down";
dropbtn.append(idk);

var dropDownContent = document.createElement("div");
dropDownContent.className = "dropdown-content";
dropDownContent.id = "myDropdown";
navbar.append(dropDownContent);

var try1 = document.createElement("a");
dropDownContent.append(try1);

var try2 = document.createElement("a");
dropDownContent.append(try2);

var try3 = document.createElement("a");
dropDownContent.append(try3);

function myFunction() {
  document.getElementById("myDropdown").classList.toggle("show");
}

window.onclick = function(e) {
  if (!e.target.matches('.dropbtn')) {
  var myDropdown = document.getElementById("myDropdown");
    if (myDropdown.classList.contains('show')) {
      myDropdown.classList.remove('show');
    }
  }
}

it does show the navbar, the color link, the genre link and the dropdown button. But there is nothing that drops down when I click on it... Could someone explain me how to solve this? (sorry for the load of code, but maybe there is something else I'm missing and I'm new to this site.)

This line in function execute when clicking on the button:

document.getElementById("myDropdown").classList.toggle("show");

So the class "show" is the key. You need to add some css for class "show" for "myDropdown", so the dropdown will show if it has class "show" and hide if not.

Something like:

#myDropdown {
  display: none;
}
#myDropdown.show {
  display: block;
}

You can use js to archive css above with ElementCSSInlineStyle.style

A Component should be unrelated to other elements or parts of the application.
If you're building a custom Dropdown - stick to it. Insert it where needed.

Here's just an idea / example of a component Class to be used like:

const myDropDown = new ComponentDropdown(ElementTarget, {/*options*/});

with the help of some utility functions to query or create Elements:

 // Utility - DOM Helper functions const Q = (s, E) => (E||document).querySelector(s); // Query Element const QA = (s, E) => (E||document).querySelectorAll(s); // Query Elements const E = (s, a) => Object.assign(document.createElement(s),a||{}); // Create El. const A = (E, o) => Object.entries(o).forEach(([p, v]) => E.setAttribute(p,v)); // El. attr /** * Component\\Dropdown * @param {Node} parent - Target node of insertion * @param {Object} options - Component options */ class ComponentDropdown { constructor (parent, options) { Object.assign(this, { E: {parent}, isOpen: false, text: "Select…", items: [], }, options); this.init(); } init() { this.E.main = E("div", {className:"dropdown"}); this.E.button = E("button", {className:"dropdown-button", type:"button", textContent: this.text}); this.E.content = E("div", {className:"dropdown-content"}); this.E.items = this.items.reduce((DF, E) => (DF.append(E), DF), new DocumentFragment()); this.E.main.append(this.E.button, this.E.content); this.E.content.append(this.E.items); this.E.button.addEventListener("click", () => this.toggle()); document.addEventListener("click", (ev) => { if (this.isOpen && !ev.target.closest(".dropdown")) this.toggle(); }); this.render(); } toggle() { this.isOpen = !this.isOpen; this.E.main.classList.toggle("is-open", this.isOpen); } render() { this.E.parent.append(this.E.main); } destroy() { this.E.main.remove(); } } const DD1 = new ComponentDropdown(Q("#DD1"), { text: "Other", items: [ E("a", {textContent: "About", href: "#"}), E("a", {textContent: "Something", href: "#"}), E("a", {textContent: "Projects", href: "#"}), E("hr"), E("a", {textContent: "Contact", href: "#"}), ] }); // DD1.toggle(); // if you want to render as opened // DD1.destroy(); // Use to remove dropdown from DOM
 /* navbar demo */ .navbar { display: flex;} .navbar>* {padding: 0 10px;} /* Component\\Dropdown */ .dropdown { display: block; position: relative; } .dropdown-content { display: none; position: absolute; top: 100%; left: 0; z-index: 9999; white-space: nowrap; background:#fff; box-shadow: 0 5px 10px rgba(0,0,0,0.3); } .dropdown.is-open .dropdown-content { display: block; padding: 5px 0; } .dropdown-content a{ display: block; padding: 0.3em 1em; white-space: nowrap; text-decoration: none; } .dropdown-content hr{ height: 1px; border: 0; margin: 5px 0; padding: 0; background: #ddd; } .dropdown-content a:hover{ box-shadow: inset 3px 0 #0bf; } .dropdown-button::after { content: "\\25be"; margin-left: 0.4em; }
 <div class="navbar"> <a href="#home">Home</a> <a href="#news">News</a> <div id="DD1"></div> </div>

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