Ir para conteúdo
Givanildo_Silva

Função Javascript não reconhece Class de Polyline SGV criada dinamicamente com Javascript

Recommended Posts

 

Srs sou principiante na Linguagem Javascript e estou tendo dificuldades em implementar um projeto, peço ajuda .

Neste projeto crio dinamicamente  com Javascript polylines dentro de um SVG, cada polyline e criada com duas Classes (draggable e tooltip), a Class draggable é reconhecida normalmente, mas a tooltip não é reconhecida, quando a tag polyline com as classes é adicionada normalmente dentro do index funciona corretamente.

 

abaixo códigos do projeto:

 

Função ocultar polyline:

let valor;

let checagem;

function teste(checkbox) {

    valor = checkbox.value;
    checagem = checkbox.checked;
}

function ocultar(){

    let polyline = document.getElementsByTagName("polyline");       
    let equipe = document.getElementsByName("equipe");



        if(checagem === true){

            for(j=0;j<polyline.length;j++){
                if(polyline[j].getAttribute("name")=== valor){
                    polyline[j].setAttributeNS(null, "visibility", "hidden");
                }
            }
            
        }

        if(checagem ===false){

            for(j=0;j<polyline.length;j++){
                if(polyline[j].getAttribute("name")===valor){
                    polyline[j].setAttributeNS(null, "visibility", "visible");
                }
            }
            
        }
    
           
 


}
<!DOCTYPE html>
<html lang="pt-br">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">         
        <link rel="stylesheet" href="_css/estilo_principal.css">
        <script src="js/arrastar.js"></script>
        <script src="js/tooltip.js"></script>
        <script src="js/ocultar.js"></script>
        

        <title>Painel Diagrama</title>
    </head>
    <body>

        <div id="painel">

            <input type="button" value="Desenhar" onclick="criarlinha()"/>
             
            <div id="itens" class="w3-container">
                <div class="w3-dropdown-hover">
                    <input type="button" id="equipe-1" value="Equipes" title="Selecione uma Equipe para oculta-lá"/> 
                    <div  class="w3-dropdown-content w3-bar-block w3-border">
                        <ul id="equipes">

                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div id="diagrama" >
            <svg id="tela" width="14800px" height="2640px"  viewBox="0 0 14800 2640" onload="makeDraggable(evt); tooltip(evt)">


                <g id="tooltip" visibility="hidden" >
                    <rect x="2" y="2" width="80" height="85" fill="black" opacity="0.4" rx="2" ry="2"/>
                    <rect width="80" height="85" fill="grey" rx="2" ry="2"/>
                    <text x="4" y="6">Tooltip</text>
                    <line x1="2" y1="23" x2="170" y2="23" stroke="black" stroke-width="2"></line>
                    <text x="4" y="26">Tooltip</text>
                    <line x1="2" y1="43" x2="170" y2="43" stroke="black" stroke-width="2"></line>
                    <text x="4" y="46">Tooltip</text>
                    <line x1="2" y1="63" x2="170" y2="63" stroke="black" stroke-width="2"></line>
                    <text x="4" y="66">Tooltip</text>
                </g>
               <polyline class="draggable tooltip" name="teste" points="885 980 1200 980" stroke="green"  stroke-width="10" fill="none"  equipe="Equipe: Teste" os="os: 27493/2019" trecho="Trecho: Teste1" fiscal="Fiscal: Fulano de Tal"/>


            </svg>
            
        </div>       
                    
        
        <script src="js/linhasvg.js"></script>

    </body>
    

</html>

Função tooltip:

function tooltip(evt) {
    var svg = document.getElementById('tela');
    var tooltip = svg.getElementById('tooltip');
    var tooltipText = tooltip.getElementsByTagName('text')[1];
    var tooltipText1 = tooltip.getElementsByTagName('text')[0];
    var tooltipText2 = tooltip.getElementsByTagName('text')[2];
    var tooltipText3 = tooltip.getElementsByTagName('text')[3];
    var tooltipRects = tooltip.getElementsByTagName('rect');
    var triggers = svg.getElementsByClassName('tooltip');
    var line = svg.getElementsByTagName('line');
    
    for (var i = 0; i < triggers.length; i++) {
        triggers[i].addEventListener('mousemove', showTooltip);
        triggers[i].addEventListener('mouseout', hideTooltip);			
    }

    function showTooltip(evt) {
        var CTM = svg.getScreenCTM();
        var x = (evt.clientX - CTM.e + 6) / CTM.a;
        var y = (evt.clientY - CTM.f + 20) / CTM.d;
        tooltip.setAttributeNS(null, "transform", "translate(" + x + " " + y + ")");
        tooltip.setAttributeNS(null, "visibility", "visible");

        tooltipText.firstChild.data = evt.target.getAttributeNS(null, "equipe");
        tooltipText1.firstChild.data = evt.target.getAttributeNS(null, "os"); 
        tooltipText2.firstChild.data = evt.target.getAttributeNS(null, "trecho"); 
        tooltipText3.firstChild.data = evt.target.getAttributeNS(null, "fiscal");       
        var length = tooltipText.getComputedTextLength();
        for (var i = 0; i < tooltipRects.length; i++) {
            tooltipRects[i].setAttributeNS(null, "width", length + 15);
            line[i].setAttributeNS(null,"x2",length + 15)
        }
    }

Função linhasvg:

let svg = document.querySelector("svg");


let status = true;

function criarlinha(){

    let linha = document.createElementNS("http://www.w3.org/2000/svg","polyline");

    let pontos = [];

    let equipes = document.getElementsByTagName("li")
    let equipe = prompt("Informe o nome do Setor.")

    let checar = document.getElementsByClassName("equipe")




    for (let i = 0; i < 4; i ++ ){
        pontos.push(Number(prompt("Informe os valor")));
    }
    linha.setAttribute("class","draggable tooltip");
    linha.setAttribute("name",equipe);
    linha.setAttribute( "points", pontos);
    linha.setAttribute("fill", "none");
    linha.setAttribute("stroke","green");
    linha.setAttribute("stroke-width", 6);
    linha.setAttribute("equipe",equipe)
    linha.setAttribute("os","2997/2019")
    linha.setAttribute("trecho","POA/CVN")
    linha.setAttribute("fiscal","Fiscal: Fulano de Tal")

    svg.appendChild(linha);
    pontos = [];

    let quantidade_li = equipes.length

    if (quantidade_li > 0) {

        for (let i = 0; i < checar.length; i++) {

            if ( checar[i].value === equipe){
                status = false;

            }


        }

    }


    if(status !== false){
        
    
    
    
        let lis; 
    
        let ul = document.getElementById("equipes"); 
    
        let l1 = document.getElementsByTagName("li"); 
    
        let li = document.createElement("li"); 
    
        let span = document.createElement("span"); 
    
        var input = document.createElement("input"); 
    
        input.type ="checkbox"; 
    
        input.value = equipe; 
    
        input.className="equipe"; 
    
        input.name="equipe"; 

        input.setAttribute("onclick","teste(this), ocultar()")
    
        span.innerText= equipe; 

    
        ul.appendChild(li); 

        if (l1.length > 0) {

            lis = l1.length - 1; 
        }

        else{
            lis = l1.length;
        }
        l1[lis].appendChild(span); 
    
        l1[lis].before(input, span); 


        }
        let item = document.getElementsByClassName("equipe")
        let poly = document.getElementsByTagName("polyline")


        for (let i = 0; i < item.length;i++){
            for(j = 0; j < poly.length; j++){
                if (item[i].attributes[1].value === poly[j].attributes[1].value){
                    if(item[i].checked === true){
                        poly[j].setAttribute( "visibility", "hidden")

                    }

                }
            }


        }
    }

Função arrastar:

function makeDraggable(evt) {
    let svg = evt.target;

    svg.addEventListener('mousedown', startDrag);
    svg.addEventListener('mousemove', drag);
    svg.addEventListener('mouseup', endDrag);
    svg.addEventListener('mouseleave', endDrag);
    svg.addEventListener('touchstart', startDrag);
    svg.addEventListener('touchmove', drag);
    svg.addEventListener('touchend', endDrag);
    svg.addEventListener('touchleave', endDrag);
    svg.addEventListener('touchcancel', endDrag);
    svg.addEventListener('click', clicar);


    function getMousePosition(evt) {
        let CTM = svg.getScreenCTM();
        if (evt.touches) { evt = evt.touches[0]; }
        return {
            x: (evt.clientX - CTM.e) / CTM.a,
            y: (evt.clientY - CTM.f) / CTM.d

        };


    }

    let selectedElement, offset, transform;

    function startDrag(evt) {
        if (evt.target.classList.contains('draggable')) {
            selectedElement = evt.target;
            offset = getMousePosition(evt);

            // Make sure the first transform on the element is a translate transform
            let transforms = selectedElement.transform.baseVal;

            if (transforms.length === 0 || transforms.getItem(0).type !== SVGTransform.SVG_TRANSFORM_TRANSLATE) {
                // Create an transform that translates by (0, 0)
                let translate = svg.createSVGTransform();
                translate.setTranslate(0, 0);
                selectedElement.transform.baseVal.insertItemBefore(translate, 0);
            }

            // Get initial translation
            transform = transforms.getItem(0);
            offset.x -= transform.matrix.e;
            offset.y -= transform.matrix.f;
        }
    }

    function drag(evt) {
        if (selectedElement) {
            evt.preventDefault();
            let coord = getMousePosition(evt);
            transform.setTranslate(coord.x - offset.x, coord.y - offset.y);
        }

    }

    function clicar(evt) {
        if (selectedElement) {
            evt.preventDefault();
            let coord = getMousePosition(evt);
            transform.setTranslate(coord.x - offset.x, coord.y - offset.y);
        }
        alert("X= " + getMousePosition(evt).x  + " Y= " + getMousePosition(evt).y)
    }
    function endDrag(evt) {
        selectedElement = false;
    }


}

Estilo estilo_principal:

@charset "utf-8";


svg#tela{
    background: url("_imagens/diagrama.png") no-repeat;
    
}

div#diagrama{
    position: absolute;
    border: 2px solid black;
    top: 180px;
    left: 30px;
    width: 95%;
    height: 80%;
    overflow: auto;
}

div#painel{
    position: absolute;
    border: 1px solid black;
    padding: 10px;
    left: 30px;

}

div#painel input{
    text-align: center;
       
}

input#equipe-1{
    width: 150px;
    margin-left: -10px;      
}

div#itens{    
    float: right;
    width: 165px;  
}

.equipe{
    margin-left: 5px;
}

span{
    margin-left: 5px;
}

ul#equipes{    
    padding-left: 0px;
    padding-top: -15x;   
}

ul#equipes li{      
    list-style: none;    
    padding: 1px; 
    
}

svg text{
    fill: white;
}

#tooltip {
    dominant-baseline: hanging; 
}

.draggable{
    cursor: move;
}

Desde já agradeço a atenção e colaboração.

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Primeiramente seu tópico está relacionado ao elemento polyline e sua descrição ao tooltip isso deixa confuso para saber qual realmente é o seu problema:

 

 

linhasvg:

1 - remova o constructor Number afinal você deve receber uma sequencia numerica ex:"2,5,100,150" já que esse elemento espera pontos de x,y, enviando apenas um numero ex: "2" não basta para criar uma linha logo nada é exibido, o Number deve ser removido já que não essa sequencia não seja um int ou float e sim uma string

2 - foi adicionado um eventListener ao elemento criado dinamicamente afinal após o carregamento da pagina o script tooltip não é chamado novamente para que consiga identificar os novos elementos então essa alteração acredito ser inevitável

 

//Antes
function criarlinha() {
 // ...
 for (let i = 0; i < 4; i ++ ){
   pontos.push(Number(prompt("Informe os valor")));
 }
  
 linha.setAttribute("class","draggable tooltip");
 linha.setAttribute("name",equipe);
 linha.setAttribute( "points", pontos);
 linha.setAttribute("fill", "none");
 linha.setAttribute("stroke","green");
 linha.setAttribute("stroke-width", 6);
 linha.setAttribute("equipe",equipe)
 linha.setAttribute("os","2997/2019")
 linha.setAttribute("trecho","POA/CVN")
 linha.setAttribute("fiscal","Fiscal: Fulano de Tal");
}

//Depois
function criarlinha(){
  // ...
  for (let i = 0; i < 4; i ++ ){
    pontos.push(prompt("Informe os valor")); // linha modificada
  }
  
  linha.setAttribute("class","draggable tooltip");
  linha.setAttribute("name",equipe);
  linha.setAttribute( "points", pontos);
  linha.setAttribute("fill", "none");
  linha.setAttribute("stroke","green");
  linha.setAttribute("stroke-width", 6);
  linha.setAttribute("equipe",equipe)
  linha.setAttribute("os","2997/2019")
  linha.setAttribute("trecho","POA/CVN")
  linha.setAttribute("fiscal","Fiscal: Fulano de Tal");
  linha.addEventListener('mouseover', tooltip); // linha adicionada
}

 

Tooltip:

 

1 - Foi adicionado um novo evento para que o tooltip seja exibido após o evento hover no polyline criado

2 - Foi adicionado o método hideTooltip já que estava faltando no código postado nesse post

function tooltip(evt) {
  // ....
  for (var i = 0; i < triggers.length; i++) {
    triggers[i].addEventListener('mousemove', showTooltip);
    triggers[i].addEventListener('mouseout', hideTooltip);
    triggers[i].addEventListener('mouseover', showTooltip); // linha adicionada
  }
  
  // ...
  function hideTooltip(evt) { // metodo adicionado
    tooltip.setAttributeNS(null, "visibility", "hidden");
  }
}

Ex: https://playcode.io/481497?tabs=tooltip.js,preview

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar Agora

  • Conteúdo Similar

    • Por violin101
      Caros amigos, saudações.
       
      Estou com uma pequena dúvida, referente a PEGAR AUTOMATICAMENTE a HORA e alimentar o campo INPUT.
       
      Tenho uma rotina, que estava aparentemente funcionando corretamente, mas agora estou tendo problema.
       
      A rotina, pega a HORA atual e informa automaticamente o INPUT, não estou entendendo porque agora não está mais fazendo.

      Abaixo a rotina.

       
      <div class="col-lg-3"> <label for="cotaHrsinicio">Hora da Abertura<span class="required">*</span></label> <div class="controls"> <input type="time" id="cotaHrsinicio" name="cotaHrsinicio" class="form-control" style="width:100%;" value="" /> <!-- NESSE INPUT A ROTINA INFORMA A DATA ATUAL --> </div> </div>  
       
      function date_time() { var date = new Date(); //var am_pm = "AM"; var hour = date.getHours(); /* if(hour>=12){ am_pm = "PM"; } */ if (hour == 0) { hour = 12; } if(hour<12){ hour = hour - 12; } if(hour>12){ hour + 12; } if(hour<10){ hour = "0"+hour; } var minute = date.getMinutes(); if (minute<10){ minute = "0"+minute; } var sec = date.getSeconds(); if(sec<10){ sec = "0"+sec; } /* *Formato da Hora (h:m:s) * Passar para a Variável: Hora Atual */ var cotaHrsinicio = document.getElementById("cotaHrsinicio").value = hour+":"+minute; }
      Grato,
       
      Cesar

       
    • Por luiz monteiro
      Bom dia.
      Estou precisando formatar um campo de entrada type text somente para numero com a seguinte formatação.
      se menor que 999 mostrar dessa forma mesmo, nesse caso seria para centena.dezena.unidade. Tipo 001 até 009 depois 010 até 099 depois 100 até 999
      de 1.000 até 999.999  mostrar com o ponto, nesse caso seria para milhar.centena.dezena.unidade. Tipo 001.000 até 001.999 e assim por diante.
      de 1.000.000 até 9.999.000, nesse caso seria para milhão.milhar.centena.dezena.unidade. aqui mesma ideia....
      Parecidos com aqueles campos de preço, que ao digitar os zeros ficam a esquerda até o valor atingirem a unidade correspondente.
       
      Tentei adaptar esse que encontrei na net.
      function moeda(a, e, r, t) { let n = "" , h = j = 0 , u = tamanho2 = 0 , l = ajd2 = "" , o = window.Event ? t.which : t.keyCode; if (13 == o || 8 == o) return !0; if (n = String.fromCharCode(o), -1 == "0123456789".indexOf(n)) return !1; for (u = a.value.length, h = 0; h < u && ("0" == a.value.charAt(h) || a.value.charAt(h) == r); h++) ; for (l = ""; h < u; h++) -1 != "0123456789".indexOf(a.value.charAt(h)) && (l += a.value.charAt(h)); if (l += n, 0 == (u = l.length) && (a.value = ""), 1 == u && (a.value = "0" + r + "0" + l), 2 == u && (a.value = "0" + r + l), u > 2) { for (ajd2 = "", j = 0, h = u - 3; h >= 0; h--) 3 == j && (ajd2 += e, j = 0), ajd2 += l.charAt(h), j++; for (a.value = "", tamanho2 = ajd2.length, h = tamanho2 - 1; h >= 0; h--) a.value += ajd2.charAt(h); a.value += r + l.substr(u - 2, u) } return !1 } Mas sem sucesso.
       
      Grato por enquanto.
       
       
       
    • Por Giovanird
      O script abaixo atualiza a página (centro.php) a cada um minuto e dentro desta página terei uma div que não poderá ser atualizada.
      Tentei colocar esta div como pagina com setInterval de 100 minutos porem ao dar o refresh no centro.php  tudo vai junto.  Será que isto é possivel?

      Desde já meu muito obrigado!
      <script> function atualiza(){ var url = 'centro.php'; $.get(url, function(dataReturn) { $('#centro').html(dataReturn); }); } setInterval("atualiza()",60000); </script>  

    • Por luiz monteiro
      Bom dia. Eu estou tentando encontrar uma maneira de evitar que após o usuário selecionar, se selecionar, uma imagem, essa seja substituída apenas por outra selecionada. Porém quando o usuário cancela a seleção, o input file remove o arquivo se já foi selecionado anteriormente.
      Essa é a estrutura que estou usando HTML
      form action="#" method="post" name="formulario" id="formulario" enctype="multipart/form-data"
      input type="file" name="file_name[]" br input type="file" name="file_name[]" br button enviar /button /form
      JS PURO
      Peguei esse script em um post aqui do stackoverflow e adaptei
      script type="text/javascript"
      let formulario = document.querySelector("#formulario"); formulario.addEventListener("change", (e)=>{ e.preventDefault(); var file = e.target.files[0]; if (e.target.files.length === 1 && e.target.files !== undefined && e.target.files !== null && file.type.match('image.*')) { console.log("if okay"); } else { //preciso entender o que devo fazer aqui para verificar se há arquivo no DOM desse target caso, o usuário cancele a seleção, para evitar que se há um arquivo no DOM esse permaneça. console.log(file); //CASO O USUÁRIO CANSELA A SELEÇÃO, RETORNA undefined } }); /script
      O if está correto, porém o que falta é o que fazer no else. Agradeço desde já.
    • Por ILR master
      Fala pessoal, tudo bem?
       
      Tô tentando fazer um pre-loading, mas não consigo de jeito algum.
      Quero mostrar uma animação enquanto a página é carregada e depois de caregada, esconder a animação e mostrar conteúdo.
       
      Aguém pode me ajudar?
       
      Segue código abaixo
       
       
      <!DOCTYPE html>
      <html lang="pt-br">
      <head>
          <meta charset="utf-8">
          <meta name="viewport" content="width=device-width, initial-scale=1.0" />  
          <title>PÁGINA LOAD</title>

      <style type="text/css">
      .loadclass {
          border: 2px solid #f3f3f3; /* Light grey */
          border-top: 4px solid #ffc401; /* Blue */
          border-radius: 50%;
          width: 50px;
          height: 50px;
          animation: spin 2s linear infinite;
      }
      @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
      }
      .conteudo {
          display:none;
      }
      </style>
      <script>
          function loading(){
              document.getElementsByClassName('loadclass')[0].style.display="none";
              document.getElementsByClassName('conteudo').style.display="block";
          }
      </script>
      </head>
      <body onLoad="loading()">
      <div class="loadclass"></div>
      <div class="conteudo">SEU CONTEUDO AQUI DENTRO!!!</div>
      </body>
      </html>
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.