2012-02-04 5 views
1

키보드 탐색 기능으로 사이트를 구축하려고합니다. 사용자가 왼쪽 및 오른쪽 화살표를 사용하여 5 또는 6 페이지의 메뉴를 탐색 할 수있게하려고합니다. 왼쪽/오른쪽 화살표를 눌렀을 때 사용자가 어떤 페이지에 있더라도 메뉴에서 앞으로/뒤로 이동하기를 원합니다. 키보드 탐색 : 화살표 키로 다음 요소와 이전 요소로 이동하는 방법?

는의 수평 메뉴는이 방법을 구축한다고 가정 해 봅시다 :
[홈/임의 문서/일부 페이지// 그리고 또 다른 페이지]

은 분명히이 작동하지 않습니다. 여기에 지금까지 무엇을 가지고 :

document.onkeyup = KeyCheck;  

var pages = ["index.php", "random-page.php", "some-page.php", "another-page.php", "and-so-on.php"]; 

function leftarrowpressed() { 
    location.href = pages[0]-1; 
} 

function rightarrowpressed() { 
    location.href = pages[0]+1; 
    } 
} 

function KeyCheck(e) 
    { 
     var KeyID = (window.event) ? event.keyCode : e.keyCode; 

     switch(KeyID) 
     { 

// left arrow key 
     case 37: 
     leftarrowpressed()  
      break; 

// right arrow key 
      case 39: 
      rightarrowpressed() 
      break; 

     } 
    } 

는 당신의 도움에 대해 감사합니다.

답변

1

pages[0]-1NaN"index.php"-1으로 평가됩니다. 페이지 URL에서 1을 빼는 것은 원하지 않습니다 (기본적으로 문자열에서 빼기는 불가능합니다). 색인에서 1을 뺀 다음 이전 페이지를 가져옵니다. 또한, 경계에 대한 보호 :

location.href = pages[ Math.max(0, 0 - 1) ]; 

과 :

location.href = pages[ Math.min(pages.length - 1, 0 + 1) ]; 

을 당신이 자동으로 현재 페이지의 인덱스로 0 교체 같아요.

둘째로, }rightarrowpressed 인 것으로 보입니다.

+0

이것은 꽤 빠릅니다. 맞습니다. NaN 오류가 발생했다는 점을 잊어 버렸습니다. 글쎄, 그것은 한 번만 작동하는 것 같습니다. 두 번째로 오른쪽 화살표를 누르면 아무 것도하지 않습니다. – Macxim

+0

"_ 현재 페이지의 색인으로 0을 자동으로 바꿉니다 ._">> 어떻게 할 수 있습니까? – Macxim

+0

@Macxim : 나는 각 페이지에이 코드 조각이 있다고 가정하고'index.php'에이 코드 조각을'0'으로,'random-page.php'에'1'을 넣었습니다 등, 그래서'random-page.php'에 왼쪽 화살표를 사용하면'index.php'로 이동할 것입니다. – pimvdb

0

글쎄, 당신은 현재 어떤 페이지가 현재 작동하는지 알아야 할 것 같습니다. 이 경우 window.localStorage를 권하고 싶습니다. A) 모든 페이지가 동일한 도메인에서 제공되는 경우에만 B) 이전 브라우저를 지원할 필요가 없습니다. 그 중 하나가 사실이 아니라면이 방법은 작동하지 않으며 URL 문자열을 구문 분석하는 등의 다른 작업을 수행해야합니다.

코드를 가져 와서 localStorage 사용 방법을 약간 수정했습니다. 나는 몇 가지 코멘트를 추가했지만 상대적으로 자명하다. 여기에 :

//if current index don't exist, make it 
if (!window.localStorage.currentPageIndex) 
{ 
    window.localStorage.currentPageIndex = 0;//frustratingly, it gets stringified anyway - you have to parseInt later 
} 

//set up vars 
var pages  = ["index.php", "random-page.php", "some-page.php", "another-page.php", "and-so-on.php"], 
currentPageIndex = parseInt(window.localStorage.currentPageIndex);//as promised 

//set event listener on window 
window.addEventListener("keyup", KeyCheck); 
function KeyCheck(e) 
{ 
    var KeyID = (window.event) ? event.keyCode : e.keyCode; 

    switch(KeyID) 
    { 
      // left arrow key 
     case 37: 
      if (currentPageIndex == 0)//we're at the first page, go to the last 
       currentPageIndex = pages.length - 1;//-1 to account for first index being "0" 
      else//go to the previous page 
       currentPageIndex--; 
      break; 
      // right arrow key 
     case 39: 
      if (currentPageIndex == (pages.length - 1))//if we're at the last page, go to the first 
       currentPageIndex = 0; 
      else//go to the next page 
       currentPageIndex++; 
      break; 
     default: 
      var noChange = true;//just so we can ignore the rest if a boring key 
    } 

    if (!noChange)//haha, I love double negatives 
    { 
     //now dump the new current page index back into localStorage 
     window.localStorage.currentPageIndex = currentPageIndex; 

     //first, try it in your javascript console to make sure it works (refresh the page!) 
     console.log(pages[currentPageIndex],currentPageIndex); 
     //then use real urls and uncomment the next line to go to the new current page! 
     //location.href = pages[currentPageIndex] 
    } 
} 

그러나 나는 정말로 묻습니다.이 방법으로 정말로하고 싶습니까? 이는 많은 HTTP 요청과 페이지 새로 고침입니다. 한 번에 한꺼번에로드 할 수있을만큼 작은 페이지입니까? (페이지 사이에 멋진 미끄러지거나 미친듯한 3D 효과를 줄 수도 있습니다 - 다시 말하면 새로운 브라우저 만 지원할 필요가 있다고 가정하면 ...)

+0

편집 전에이 게시물을 발견 한 경우 죄송합니다. 현재 작동합니다. 내가해야할만큼 철저히 시험해 보지 못했습니다 ... (주말에 게으름을 피울 수 있습니다!) – JKing

+0

내 목적은 메뉴를 탐색 할 수있는 대안을 제공하면서 접근성을 향상시키는 것입니다. 결과 [여기] (http://maximelaforet.com/)를 확인할 수 있습니다. 나는 또한이 문제에 대해 당신의 의견을 듣고 싶습니다. 그리고 렌더링에 대한 리뷰. 이런 식으로 진행하는 것은 나쁜 생각입니까? – Macxim

+0

의견에 모두 들어 맞지 않아서 새로운 대답을 게시 할 것입니다 ... – JKing

1

괜찮습니다. 사이트를 체크 아웃하고 코드를 약간 수정/확장했습니다. (거의) 당신이하고 싶은 생각을 달성하십시오. 아마이 일을하는 데 더 좋은 방법이 무엇인지 보여주기 때문에 다른 대답은 편집하지 않고 남겨 둘 것입니다 ...이 솔루션은 오히려 해킹 -y이며 개념을 설명하는 방법 일뿐입니다.

블로그 페이지를보고 블로그 페이지를 제외한 다른 페이지로 이동 한 다음 웹킷 관리자를 엽니 다 (내 코드는 WebKit (크롬/사파리)에서만 작동합니다. 실제로 작동시키기는 쉽지만 모든 브라우저에서)와 입력 자바 스크립트 콘솔에 다음

document.querySelector("footer").setAttribute("style","position:fixed;bottom:0px;width:100%;"); 
    document.querySelector("header").setAttribute("style","position:fixed;top:0px;width:100%;"); 

    var pages   =  ["accueil","references","cv","contact","aide","blog"], 
    classNames   =  ["accueil","ref","cv","contact","aide","blog"], 
    pageUrls   =  ["","references.php","cv.php","contact.php","aide.php","blog/"] 
    baseUrl    =  "http://maximelaforet.com/", 
    currentPageIndex =  pageUrls.indexOf(window.location.href.replace(baseUrl,"")), 
    pageDivs   =  [1,1,1,1,1,1]; 

    pageDivs[currentPageIndex] = document.querySelector("div.content"); 
    pageDivs[currentPageIndex].id = pages[currentPageIndex]+"Page"; 
    pageDivs[currentPageIndex].setAttribute("style","-webkit-transition:all 1s ease-in-out;position:fixed;top:63px;width:100%;height:"+(window.innerHeight - 270)+"px;overflow:scroll;"); 

    for (var i=0; i<pageUrls.length;i++) 
    { 
     if (i!=currentPageIndex) 
     { 
      var pageGrabber = new XMLHttpRequest(); 
      pageGrabber.open("GET","http://maximelaforet.com/" + pageUrls[i], false); 
      pageGrabber.send(null); 

      if (pageGrabber.status==200) 
      { 
       var temp = document.createElement("div"); 
       temp.innerHTML = pageGrabber.response; 

       if (pages[i]!="blog") 
       pageDivs[i] = temp.querySelector("div.content").cloneNode(true); 
       else 
       pageDivs[i] = temp.querySelector("div#page").cloneNode(true); 
      } 

      pageDivs[i].id = pages[i]+"Page"; 
      pageDivs[i].setAttribute("style","-webkit-transition:-webkit-transform 1s ease-in-out;position:fixed;top:63px;width:100%;height:"+(window.innerHeight - 270)+"px;overflow:scroll;"); 
      if (i<currentPageIndex) 
      pageDivs[i].style.webkitTransform = "translate3d(-100%,0,0)"; 
      else 
      pageDivs[i].style.webkitTransform = "translate3d(100%,0,0)"; 

      document.body.appendChild(pageDivs[i]); 
     } 
    } 

    window.addEventListener("keyup", KeyCheck, true); 
    function KeyCheck(e) 
    { 
     e.preventDefault(); 
     e.stopPropagation(); 
     var KeyID = (window.event) ? event.keyCode : e.keyCode; 

     switch(KeyID) 
     { 
      // left arrow key 
      case 37: 
      if (currentPageIndex == 0)//we're at the first page, go to the last 
      currentPageIndex = pages.length - 1;//-1 to account for first index being "0" 
      else//go to the previous page 
      pageDivs[currentPageIndex].style.webkitTransform = "translate3d(100%,0,0)"; 
      pageDivs[currentPageIndex-1].style.webkitTransform = "translate3d(0,0,0)"; 
      document.querySelector("header").classList.remove(classNames[currentPageIndex]); 
      document.querySelector("header").classList.add(classNames[currentPageIndex-1]); 

      if (classNames[currentPageIndex] == "accueil") 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_acc"); 
      else 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_"+classNames[currentPageIndex]); 
      if (classNames[currentPageIndex] == "accueil") 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex-1]+"']").classList.toggle("current_acc"); 
      else 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex-1]+"']").classList.toggle("current_"+classNames[currentPageIndex-1]); 

      currentPageIndex--; 
      break; 
      // right arrow key 
      case 39: 
      if (currentPageIndex == (pages.length - 1))//if we're at the last page, go to the first 
      currentPageIndex = 0; 
      else//go to the next page 
      pageDivs[currentPageIndex].style.webkitTransform = "translate3d(-100%,0,0)"; 
      pageDivs[currentPageIndex+1].style.webkitTransform = "translate3d(0,0,0)"; 

      document.querySelector("header").classList.remove(classNames[currentPageIndex]); 
      document.querySelector("header").classList.add(classNames[currentPageIndex+1]); 

      if (classNames[currentPageIndex] == "accueil") 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_acc"); 
      else 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex]+"']").classList.toggle("current_"+classNames[currentPageIndex]); 
      if (classNames[currentPageIndex] == "accueil") 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex+1]+"']").classList.toggle("current_acc"); 
      else 
      document.querySelector("li > a[class~='"+classNames[currentPageIndex+1]+"']").classList.toggle("current_"+classNames[currentPageIndex+1]); 

      currentPageIndex++; 
      break; 
      default: 
      var noChange = true;//just so we can ignore the rest if a boring key 
     } 

    } 

염두에 두어야는하지만,이 그것을 할 수있는 정말 해킹-Y 방법이지만, 그것은 올바른 방향을 가리켜 야합니다. 더 궁금한 점이 있으면 알려주세요.

+0

귀하의 솔루션은 정말로 인상적입니다. 고맙습니다! 그러나, 나는 당신이 내 사이트를 확인했을 때, 당신은 @ pimvbd의 해결책의 결과를 아래에서 보았다고 믿는다. 그거에 대해서 어떻게 생각해? HTTP 요청 및 새로 고침의 양을 줄입니까? JS 페이지를 각 페이지에 가지고있는 것이 좋지 않습니까? 게다가 그의 솔루션은 모든 브라우저에서 작동합니다. – Macxim

+0

그의 솔루션은 사용자가 새 페이지로 전환 할 때마다 HTTP 요청을 수행하고 페이지를 새로 고치며 각 페이지마다 약간 다른 코드가 필요합니다. 여기서 제공 한 솔루션은 몇 가지 HTTP 요청을 먼저 수행하지만 페이지를 새로 고치지는 않으며 각 페이지에서 동일한 코드를 사용할 수 있습니다. 이상적인 솔루션은 모든 페이지를 하나로 결합하여 이와 유사한 솔루션을 사용하는 것입니다. 그렇게하면 HTTP 요청이 하나만 필요하므로 새로 고칠 필요가 없습니다. (또한, 내 솔루션은 모든 브라우저에서 작업하기가 쉽습니다. 5 ~ 10 분 정도면 효과가 있습니다.) – JKing

관련 문제