windows位置href到div(id)

时间:2017-12-01 09:54:18

标签: javascript

如何使window.location转到同一页面,但使用另一个不同的div标签。 (例如:href ="#div1")。



function gotoDiv(){
    var gotoDivID=Math.round(Math.random()*2)
    var links=new Array()
    links[0]="#div1"
    links[1]="#div2"
    links[2]="#div3"
         window.location=links[gotoDivID]    }

<form><input type="button" value="go to div" onClick="gotoDiv()"></form>
</br></br>
 
<div id="div1" style="width:40px; height:45px; background:blue; color:#fff;">Div1</div>
<div id="div2" style="width:40px; height:45px; background:purple; color:#fff">Div2</div>
<div id="div3" style="width:40px; height:45px; background:orange; color:#fff;">Div3</div>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

试试这个

function gotoDiv() {
  var links = Array.from(document.querySelectorAll("div[id]")).map(ele => ("#" + ele.innerHTML.toLowerCase())); //get an array of div's innerHTML prefixed with #
  //console.log( links );
  var gotoDivID = Math.floor(Math.random() * links.length); //get a random value between 0 and number of divs
  //console.log(gotoDivID);
  location.hash = links[gotoDivID];
}

<强>演示

&#13;
&#13;
function gotoDiv() {
  var links = Array.from(document.querySelectorAll("div[id]")).map(ele => ("#" + ele.innerHTML.toLowerCase())); //get an array of div's innerHTML prefixed with #
  //console.log( links );
  var gotoDivID = Math.floor(Math.random() * links.length); //get a random value between 0 and number of divs
  //console.log(gotoDivID);
  location.hash = links[gotoDivID];
}
&#13;
div {
  margin-top: 400px;
}
&#13;
<form><input type="button" value="go to div" onClick="gotoDiv()"></form>
</br>
</br>

<div id="div1" style="width:40px; height:45px; background:blue; color:#fff;">Div1</div>
<div id="div2" style="width:40px; height:45px; background:purple; color:#fff">Div2</div>
<div id="div3" style="width:40px; height:45px; background:orange; color:#fff;">Div3</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

应用Math.round并不是您想要的。 Math.random()返回0&lt; = x&lt; 1,所以只需乘以div的计数并截断为int。

您可以使用window.location.hash直接设置哈希。

function gotoDiv(){
  var divs =  ["div1", "div2", "div3"];
  var hash = divs[parseInt(Math.random()*divs.length)];
  window.location.hash = hash;
  // output to see something here 
  console.info(hash)
}
gotoDiv();
<form><input type="button" value="go to div" onClick="gotoDiv()"></form>
</br></br>
 
<div id="div1" style="width:40px; height:45px; background:blue; color:#fff;">Div1</div>
<div id="div2" style="width:40px; height:45px; background:purple; color:#fff">Div2</div>
<div id="div3" style="width:40px; height:45px; background:orange; color:#fff;">Div3</div>