Apps Script公式リファレンス: Apps Script Reference |障害・課題追跡: IssueTracker |Google Workspace: Status Dashboard - Summary

2018年9月8日土曜日

セレクトボックスの選択肢に応じて指定した要素をスクロールさせたい


selectの選択肢に応じてdiv要素をスクロールしたい

ついでに上下ボタンでもスクロールさせてみる



Bloggerの記事の中ではうまく動作しなかったのでデモアプリを用意しました

デモ
https://script.google.com/macros/s/AKfycbxMlOTqLMMfUmC0Ink4SU9jNl7mpNJzoawJcKh1tQrF1bcs3uw/exec



コード.gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile("index");
}
意訳
この機能がやること
指定したHTMLファイルを表示する




index.html
<html>
<head>
  <style>
    #overflow_scroll {
      width: 240px;
      height: 40px;
      overflow: scroll;
      border: solid 1px lightgray;
    }
  </style>
</head>
<body>
  <div id="overflow_scroll">
    <div id="a">あいうえお</div>
    <div id="ka">かきくけこ</div>
    <div id="sa">さしすせそ</div>
    <div id="ta">たちつてと</div>
    <div id="na">なにぬねの</div>
  </div>
  <select id="akasatana">
    <option value="a">あいうえお</option>
    <option value="ka">かきくけこ</option>
    <option value="sa">さしすせそ</option>
    <option value="ta">たちつてと</option>
    <option value="na">なにぬねの</option>
  </select>
  <button id="prev_bt">▲</button>
  <button id="next_bt">▼</button>
  <script>
    var akasatana = elem("akasatana");
    var overflow_scroll = elem("overflow_scroll");

    akasatana.onchange = akasatana_onchange;
    prev_bt.onclick = function() {prev_next_click(-1)};
    next_bt.onclick = function() {prev_next_click(1)};

    function elem(id) {
      return document.getElementById(id);
    }

    function prev_next_click(add) {
      var index = akasatana.selectedIndex;
      akasatana.selectedIndex = index + add;
      var value = akasatana[index + add].value;
      div_scroll(value);
    }

    function akasatana_onchange() {
      var selected_index = akasatana.selectedIndex;
      var target_value = akasatana[selected_index].value;
      div_scroll(target_value);
    }

    function div_scroll(target_value) {
      var target = elem(target_value);
      var abs_pos = target.getBoundingClientRect().top - 5;
      overflow_scroll.scrollBy(0, abs_pos);
    }
  </script>
</body>
</html>


補足

window.scrollTo ではうまく行かなかったので window.scrollBy を使いました


Latest post

Google Apps Scriptの障害時はIssueTrackerを見てみる - Incidents for Apps Script are reported on Issue Tracker

IssueTracker > Apps Script issues https://issuetracker.google.com/savedsearches/566234 Google Apps Scriptの障害時は IssueTracker に課題が上がっていることが...