Управление видимостью элементов SVG - PullRequest
0 голосов
/ 03 июня 2018

Я делаю веб-проект на Java, где хочу манипулировать некоторыми внешними SVG-элементами с помощью некоторого JavaScript.

Я делаю довольно простой чертеж гаража, где у меня естьЭлемент shed со страницы JSP.

Мне нужна функция javascript, кнопка включения / выключения, где элемент может отображаться, а не скрываться.

Вот мой код:

....
<line x1="<%= Math.abs(wid+20) %>"  y1="0" x2="<%= Math.abs(wid+20) %>" y2="<%= len %>"
style="stroke:#c40d0d;
marker-start: url(#beginArrow);
marker-end: url(#endArrow);"/>  


//this is the start of the part that I want to be toggled on and off with a javascript function
<% if(shed){ %>

<rect x="<%= Math.abs(wid-200) %>" y="0" height="<%= len %>" width="200"
    style="stroke:#000000; stroke-width: 3; fill: none"/>


<rect x="<%= Math.abs(wid-200) %>" y="0" height="10" width="10"
    style="stroke:#000000; fill: #101111"/>
<rect x="<%= Math.abs(wid-10) %>" y="0" height="10" width="10"
    style="stroke:#000000; fill: #101111"/>
<rect x="<%= Math.abs(wid-200) %>" y="<%= Math.abs(len-10) %>" height="10" width="10"
    style="stroke:#000000; fill: #101111"/>
<rect x="<%= Math.abs(wid-10) %>" y="<%= Math.abs(len-10) %>" height="10" width="10"
    style="stroke:#000000; fill: #101111"/>

 <text x="<%= Math.abs((wid-200)+(wid/8)) %>" y="<%= Math.abs(len+35) %>" fill="Red"> Skur: 200.0 cm </text>

<line x1="<%= Math.abs(wid-200) %>"  y1="<%= Math.abs(len+20) %>" x2=" 
<%= wid %>" y2="<%= Math.abs(len+20) %>" 
style="stroke:#c40d0d;
marker-start: url(#beginArrow);
    marker-end: url(#endArrow);"/>  

<% } %>

</SVG>
<form action="FrontController?command=DynamicCarportSide" name="order" method="POST">
    <input type="hidden" name="length" value="<%= len %>">
    <input type="hidden" name="width" value="<%= wid %>">
    <input type="hidden" name="shed" value="<%= shed %>">
    <input type="submit" value="Side tegning">
</form>
      <%@include file="footer.jsp" %>
</body>
</html>

Я использую оператор if для отображения с или без сарая в моем jsp, но можно ли использовать кнопку щелчка для его отображения после отображения страницы

Я думал очто-то вроде этого.

function myFunction() {

var SVGcode ="//insert html code here";

document.getElementById("demo").innerHTML = SVGcode;
}

проблема в том, что SVG-код слишком велик, поэтому я не знаю, что здесь делать

РЕДАКТИРОВАТЬ:

вот изображениекак это выглядит, пока у меня просто есть функция, которая пишет Hello, когда кнопка нажата, но я хотел иметь кнопку включения, которая добавляет дополнительный SVG-код

Here is an example of an SVG-drawing without the dynamic data, only dummy data

1 Ответ

0 голосов
/ 03 июня 2018

Переключение видимости данного элемента

Вы хотели бы иметь функцию, позволяющую скрывать и отображать некоторые части SVG-элемента.Метод, который я использую, фактически работает для любого данного элемента HTML (объекта HTMLElement).Вам необходимо:

  1. указать элементы, которые вы хотите скрыть / отобразить имя класса , например:

    <line class="segments" x1="55" y1="55" ... stroke-dasharray: 10 5"/>
    <line class="segments" x1="550" y1="55" ... stroke-dasharray: 10 5"/>
    
  2. запись функция для переключения видимости данного элемента :

    • мы создадим функцию hide(), чтобы скрыть HTMLElement

      const hide = e => e.style.display = 'none'
      
    • и функция show(), чтобы показать это ...

      const show = e => e.style.display = ''
      
    • наконец, функция для управления переключателем:

      const toggleHide = function(selector) {
        [...document.querySelectorAll(selector)].forEach(e => e.style.display ? show(e) : hide(e))
      }
      
  3. Наконец триггер для вызова функции , мы можем использовать button:

    <button onclick="toggleHide('.frame')">Toggle frame</button>
    

    Установите функцию для вызова в атрибуте onclick кнопки и задайте в качестве аргумента селектор (здесь .frame) элемента, с которым вы хотите связать его.IE эта кнопка будет переключать видимость всех элементов с именем класса .frame.


Демо с вашим svg рисунком

В демонстрационной версии нижеЯ добавил две кнопки, связанные с двумя группами элементов svg.Нажмите Показать фрагмент кода > Выполнить фрагмент кода > Полная страница для просмотра:

const hide = e => e.style.display = 'none'
const show = e => e.style.display = ''
const toggleHide = function(selector) {
  [...document.querySelectorAll(selector)].forEach(e => e.style.display ? show(e) : hide(e))
}
<html>

<body>
  <SVG width="780" height="600">
<rect x="0" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="55" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="110" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="165" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="220" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="275" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="330" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="385" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="440" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="495" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="550" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="605" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="660" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="715" y="0" height="600" width="55"
        style="stroke:#000000; fill: #ffffff"/>
<rect x="770" y="0" height="600" width="55"
        style="stroke:#000000; fill: none"/>
<rect x="0" y="50" height="15" width="825"
        style="stroke:#000000; fill: none"/>
<rect x="0" y="535" height="15" width="825"
        style="stroke:#000000; fill: none"/>

<rect class="frame" x="550" y="50" height="500" width="230"
        style="stroke:#000000; stroke-width: 5; fill: none"/>
<rect x="440" y="0" height="600" width="1"
        style="stroke:#000000; stroke-width: 3; fill: none"/>

<rect x="550" y="50" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="550" y="535" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="765" y="50" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="765" y="535" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="550" y="300" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="765" y="300" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="110" y="50" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="110" y="535" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="408" y="50" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
<rect x="408" y="535" height="15" width="15"
        style="stroke:#000000; fill: #101111"/>
  <line class="segments" x1="55" y1="55" x2="550" y2="550"
      style="stroke: #000000; fill:none;
      stroke-width: 6px;
      stroke-dasharray: 10 5"/>
  <line class="segments" x1="550" y1="55" x2="55" y2="550"
      style="stroke: #000000; fill:none;
      stroke-width: 6px;
      stroke-dasharray: 10 5"/>
  
  <text x="400" y="620" fill="Red">7,8 m</text>
  <text x="835" y="300" fill="Red">6 m</text>
  
  <defs>
    <marker id="beginArrow" 
    	markerWidth="9" markerHeight="9" 
    	refX="0" refY="4" 
    	orient="auto">
        <path d="M0,4 L8,0 L8,8 L0,4" style="fill: #c40d0d;" />
    </marker>
    <marker id="endArrow" 
    	markerWidth="9" markerHeight="9" 
    	refX="8" refY="4" 
    	orient="auto">
        <path d="M0,0 L8,4 L0,8 L0,0" style="fill: #c40d0d;" />
    </marker>
</defs>
<line x1="0"  y1="630" x2="825"   y2="630" 
	style="stroke:#c40d0d;
	marker-start: url(#beginArrow);
   marker-end: url(#endArrow);"/>
<defs>
    <marker id="beginArrow2" 
    	markerWidth="9" markerHeight="9" 
    	refX="0" refY="4" 
    	orient="auto">
        <path d="M0,4 L8,0 L8,8 L0,4" style="fill: #c40d0d;" />
    </marker>
    <marker id="endArrow2" 
    	markerWidth="9" markerHeight="9" 
    	refX="8" refY="4" 
    	orient="auto">
        <path d="M0,0 L8,4 L0,8 L0,0" style="fill: #c40d0d;" />
    </marker>
</defs>
<line x1="865"  y1="0" x2="865"   y2="600" 
	style="stroke:#c40d0d;
	marker-start: url(#beginArrow);
   marker-end: url(#endArrow);"/>
   
    
</SVG>

  <p>click on the buttons to remove some parts of the shed</p>

  <button onclick="toggleHide('.segments')">Toggle bars</button>
  <button onclick="toggleHide('.frame')">Toggle frame</button>

</body>

</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...