>  기사  >  웹 프론트엔드  >  JS 기술을 통해 Baidu 검색을 구현하는 방법

JS 기술을 통해 Baidu 검색을 구현하는 방법

亚连
亚连원래의
2018-06-08 14:57:452231검색

이 글에서는 바이두 검색 기능의 JS 구현을 소개합니다. 코드는 HTML 부분과 CSS 접기 스타일 부분으로 나누어져 있습니다. 구체적인 구현 코드는 이 글을 참고하세요

오늘은 JS를 사용하여 구현하겠습니다. 바이두 검색 기능은 다음과 같습니다.

HTML 부분:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <!--百度iocn图标-->
    <link rel="shortcut icon" href="https://www.baidu.com/favicon.ico" rel="external nofollow" type="image/x-icon"/>
    <title>百度一下,你就知道</title>
    <link rel="stylesheet" href="css/baidu.css" rel="external nofollow" />
    <script src="js/H.js"></script>
  </head>
  <body onload="onloads(),randomBack()">
    <p class="box">
      <p class="box_log">
        <p class="box_log_img">
          <img src="img/superlogo_c4d7df0a003d3db9b65e9ef0fe6da1ec.png"/>
        </p>
      </p>
      <p class="box_text">
        <p class="box_text_content">
          <input type="text" name="text" id="text" value="" autofocus="autofocus"/>
          <input type="button" name="bdyx" id="btn" value="百度一下" />
          <ul id="search">
            <li class="li1" id="0" onclick="iptShow(this.id)"></li>
            <li class="li1" id="1" onclick="iptShow(this.id)"></li>
            <li class="li1" id="2" onclick="iptShow(this.id)"></li>
            <li class="li1" id="3" onclick="iptShow(this.id)"></li>
            <li class="li1" id="4" onclick="iptShow(this.id)"></li>
            <li class="li1" id="5" onclick="iptShow(this.id)"></li>
            <li class="li1" id="6" onclick="iptShow(this.id)"></li>
            <li class="li1" id="7" onclick="iptShow(this.id)"></li>
            <li class="li1" id="8" onclick="iptShow(this.id)"></li>
            <li class="li1" id="9" onclick="iptShow(this.id)"></li>
          </ul>
        </p>
      </p>
    </p>
    <script type="text/javascript" src="js/index.js" ></script>
  </body>
</html>

CSS 캐스케이딩 스타일 부분:

body{/*清除浏览器自带样式*/
  margin: 0;
  padding: 0;
  /*background-repeat: no-repeat;*/
  min-width: 1200px;
}
.box{/*最大的盒子*/
  width: 100%;
  height: 100%;
  /*background: yellow;*/
  /*height: 636px;*/
}
.box_log{/*log盒子*/
  width: 100%;
  height: 250px;
  text-align: center;
}
.box_log_img{
  margin:0 auto;
  width: 300px;
  height: 150px;
}
.box_log img{
  width: 300px;
  height: 150px;
  margin-top: 38px;
  margin-bottom: 19px;
}
.box_text{/*text搜索框盒子大小*/
  width: 100%;
  height: 36px;
}
.box_text_content{
  width: 640px;
  height: 36px;
  margin: 0 auto;
}

#text{ /*input框的样式*/
  width: 540px;
  height: 36px;
  box-sizing: border-box;
  margin-top: 3px;
  text-indent: 4px;
  outline: none;
}
.log_img{/*input框中的小相机*/
  position: absolute;
  left: 62%;
  top: 35.5%;
}
#btn{ /*按钮的样式*/
  width: 100px;
  height: 36px;
  background: #3385FF;
  border: 0px;
  letter-spacing: 1px;
  color: white;
  margin-left: -5px;
  font-size: 15px;
  box-sizing: border-box;
  transform: translateY(1.5px);
  box-sizing: border-box;
}
#btn:hover{ /*当按钮hover的样式*/
  cursor: pointer;
}
#search{  /*搜索框的样式*/
  width: 540px;
  margin: 0;
  padding: 0;
  list-style: none;
  display: none;
  border: 1px solid #E3E5E4; 
}
#search li{ /*搜索框li的大小颜色*/
  line-height: 36px;
  background: white;
}
#search li:hover{ /*当li hover的样式*/
  background: #F0F0F0;
}
.li1{ /*li中的值缩进*/
  text-indent: 4px;
}

JS 부분:

var otext = document.getElementById("text"); //获取input框
ose = document.querySelector("#search"); //通过类名选择器 选择到search框
lis = document.getElementsByClassName("li1"); //获取所有的li
otext.onkeyup = function(){  //当在input框中键盘弹起发生事件
  ose.style.display = otext.value?"block":"none"; /*三目运算符,如果otext.value的值部位空,则block。*/
  var osc = document.createElement("script"); /*创建一个script标签*/
  osc.src = "https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd="+otext.value+"&cb=houxiaowei";
  /*srcipt的src值引入百度的url,然后将otext文本框中输入的内容连接到url,在后面在运行自己的方法*/
  document.body.appendChild(osc);
  /*将创建好的script标签元素放入body中*/
  /*input框中按下回车根据input的值跳转页面*/
  if(event.keyCode==13){
    /*将百度作为连接,传入input的值,并跳入新的页面*/
    window.location.href = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd="+otext.value
  }
}
var count = 0;
var search = 0;
var arr = ose.children; /*获取ose下的所有li*/
function houxiaowei(json){
  var jsonLength = 0; /*json长度的初始值*/
//          console.log(json.s);
  for(var x in json.s){  /*将循环的次数变成json的长度*/
    jsonLength++;
  }
//          console.log(jsonLength);
  for(var i=0;i<lis.length;i++){
    if(jsonLength==0){ /*如果遍历出的长度等于0,li的值为空*/
      arr[i].innerHTML = null;  
    }else{
      if(json.s[i]!=null){/*如果json[i]的值不等于空,则将它的值放入li中*/
        arr[i].innerHTML = json.s[i];
      }
    }
  }
  if(count==lis.length-1){
    count=0;
    search=0;
  }
  count++;
  search++;
}
/*单击li中的值显示在input框中*/
function iptShow(thisId){
  otext.value = arr[thisId].innerHTML;
  window.location.href = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd="+otext.value
}
otext.onclick = function(e){
  ose.style.display = "block";
  var e = event || window.event;
  e.stopPropagation();  //阻止冒泡事件,除了IE8及以下不兼容,其他浏览器都兼容
  e.cancelBubble=true; //阻止冒泡事件,IE8及以下兼容
//        alert(e);
}
/*单击body中的任意地方隐藏li*/
document.body.onclick = function(){
  ose.style.display = "none";
}
/*单击百度btn的时候触发,并跳到新的连接*/
var btn = document.querySelector("#btn");
cookies = []; 
btn.onclick = function(){
  /*获取当前input的值*/
  var otext = document.getElementById("text").value;
  /*将百度作为连接,传入input的值,并跳入新的页面*/
  if(otext=="" || otext==null){
    window.location.href = "http://127.0.0.1:8020/%E7%99%BE%E5%BA%A6/%E7%99%BE%E5%BA%A6%E9%A6%96%E9%A1%B5.html?__hbt=1516599867084";
  }else{
    window.location.href = "https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd="+otext
  }
}
/*加载页面input为空*/
function onloads(){
  var s = otext.value = null;
  $myId("text").focus();
}
function randomBack(){
  var randomBk = parseInt(Math.random()*545);
  document.body.style.background = "url(https://ss3.bdstatic.com/lPoZeXSm1A5BphGlnYG/skin/"+randomBk+".jpg?2)";
  document.body.style.backgroundSize = "100%";
}‘“

  검색 기능은 바이두의 https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy에서 구현됩니다. /su?wd="+otext.value+" &cb=houxiaowei, 이 링크의 경우 "wd" 값은 입력 상자에서 검색할 값이며 json 개체를 반환합니다. &cb의 값은 json에서 값을 추출하여 li에 넣는 데 사용되는 메서드 또는 함수입니다.

위 내용은 제가 여러분을 위해 정리한 내용입니다. 앞으로 도움이 되길 바랍니다.

관련 기사:

JS의 숫자 유형(자세한 튜토리얼)

vue에서 watch 사용법 미리 로드하기

Angular에서 브라우저 플러그인 Batarang을 사용하는 방법

위 내용은 JS 기술을 통해 Baidu 검색을 구현하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.