Ir para conteúdo
vinicius59

Dúvida de como colocar objetos na tela!

Recommended Posts

Então... há algum tempo venho pesquisando em vários sites sobre a duvida que eu tenho, ela se consiste em como eu posso fazer (2 botoes) que ao ser acionado cria-se um quadrado pequeno de uma cor que eu vou escolher! Se alguém poder responder 'Me desculpem se essa duvida não for relacionada ao php sou novo aqui'.

Compartilhar este post


Link para o post
Compartilhar em outros sites

vinicius59

Copie os códigos abaixo para os arquivos INDEX.PHP e RESULTADO.PHP e salve as imagens dentro da mesma pasta.

 

Arquivo: INDEX.PHP

<form name="formaGeo" method="POST" action="resultado.php" >
<select name="CorFormaGeometrica">
    <option value='azul' selected>Azul</option>
    <option
value='vermelho'>Vermelho</option>
    <option
value='outro'>Sem Cor</option>
</select>

<input type="submit" value="Clique aqui" />

</form>

 

Arquivo: RESULTADO.PHP

<?php
if ($_POST['CorFormaGeometrica'] == "azul") {
    echo "<img src='azul.jpg'>";
} else {
    if ($_POST['CorFormaGeometrica'] == "vermelho") {
        echo <img src='vermelho.jpg'>";
    } else {
        echo "<img src='cinza.jpg'>";
    }
}

echo "<a href='index.php'> Voltar </a>";
?>

 

Você precisa salvar as imagens com o mesmo nome que coloquei

 

azul.jpg

cinza.jpg

vermelho.jpg

 

Espero ter ajudado de alguma forma.

 

Att.

Felipe Coutinho

azul.jpg

cinza.jpg

vermelho.jpg

Compartilhar este post


Link para o post
Compartilhar em outros sites

Existem incontáveis formas de fazer algo assim, cada qual para seu cada qual.

Se você explicar melhor o que deseja poderá ter uma resposta mais coesa.

 

<div id="quadrado" style="display:none; height:50px; width:50px; background-color:red">
    Isso só aparece se clicar em algum botão
</div>

<button class="botao">Botão 1</button>
<button class="botao">Botão 2</button>

<script>
    var btn = document.getElementsByClassName('botao');
    for (var i = 0; i < btn.length; i++) {
        btn[i].addEventListener('click', function () {
            document.getElementById('quadrado').setAttribute('style', 'display:block');
        }, false);
    }
</script>

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

e para por por botões do teclado, você pode me ajudar

1 hora atrás, Omar~ disse:

Existem incontáveis formas de fazer algo assim, cada qual para seu cada qual.

Se você explicar melhor o que deseja poderá ter uma resposta mais coesa.

 


<div id="quadrado" style="display:none; height:50px; width:50px; background-color:red">
    Isso só aparece se clicar em algum botão
</div>

<button class="botao">Botão 1</button>
<button class="botao">Botão 2</button>

<script>
    var btn = document.getElementsByClassName('botao');
    for (var i = 0; i < btn.length; i++) {
        btn[i].addEventListener('click', function () {
            document.getElementById('quadrado').setAttribute('style', 'display:block');
        }, false);
    }
</script>

 

Então, eu queria certinho é esse script só que em vez de precisar selecionar, for por botão do teclado, o numero 1 seria verde o numero 2 vermelho e o numero 3 cinza, você consegue? e esqueci de colocar que tem que ficar em fileira os quadrados que eu por, e não carregar só um quadrado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Omar~

Você pode me ajudar com o seu código, apesar de eu ter entendido o funcionamento dele, no meu caso, não esta aparecendo o quadrado vermelho.

 

Será que não deveria ser assim o código:

 

<div id="quadrado" style="display:none; height:50px; width:50px; background-color:red">
    Isso só aparece se clicar em algum botão
</div>

 

<button class="botao">Botão 1</button>

 

<script>
    var btn = document.getElementsByClassName('botao');
    for (var i = 0; i < btn.length; i++) {
        btn.addEventListener('click', function () {
        document.getElementById('quadrado').style.display='';
        }, false);
    }
</script>

 

Porque essa parte no meu caso faz aparecer o texto, mas não o quadrado com a cor em questão "vermelho", achei o seu código bem legal, mas no meu caso não funcionou, poderia dar uma esplicação?

:smiley::thumbsup:

document.getElementById('quadrado').setAttribute('style', 'display:block');

vinicius59

Fiz uns ajustes no código que fiz, alterando de PHP para apenas HTML e JavaScript

Veja qual melhor lhe atende, mas lembrando o que o Omar escreveu, existem muitos jeitos de se fazer o que você quer.

Veja os exemplos que colocamos e escolha qual melhor lhe atende.

O meu novo exemplo abaixo, você não precisa nem de um arquivo PHP, basta colocar dentro de um bloco de notas e salvar com "QualquerNome.HTML", salvar e dar 2 cliques.

 

Obs.: Lembrando que o meu exemplo uso também imagens para representar o quadrado da cor escolhida, então você deve colocar as 3 imagens que coloquei no meu post anterior junto com o seu arquivo.HTML dentro de uma mesma pasta para executar corretamente:

 

Meu código com a div do código que o Omar passou que achei muito interessante:

<script>
    function exibirForma(){
    var e = document.getElementById("CorFormaGeometrica");
    var itemSelecionado = e.options[e.selectedIndex].value;
    if(itemSelecionado=="azul"){
        document.getElementById('azul').style.visibility='visible';
        document.getElementById('azul').style.display='';
        document.getElementById('cinza').style.visibility='hidden';
        document.getElementById('cinza').style.display='none';
        document.getElementById('vermelho').style.visibility='hidden';
        document.getElementById('vermelho').style.display='none';
        document.getElementById('quadrado_azul').style.visibility='visible';
        document.getElementById('quadrado_azul').style.display='';
        document.getElementById('quadrado_cinza').style.visibility='hidden';
        document.getElementById('quadrado_cinza').style.display='none';
        document.getElementById('quadrado_vermelho').style.visibility='hidden';
        document.getElementById('quadrado_vermelho').style.display='none';
    } else if (itemSelecionado=="cinza"){
        document.getElementById('azul').style.visibility='hidden';
        document.getElementById('azul').style.display='none';
        document.getElementById('cinza').style.visibility='visible';
        document.getElementById('cinza').style.display='';
        document.getElementById('vermelho').style.visibility='hidden';
        document.getElementById('vermelho').style.display='none';
        document.getElementById('quadrado_azul').style.visibility='hidden';
        document.getElementById('quadrado_azul').style.display='none';
        document.getElementById('quadrado_cinza').style.visibility='visible';
        document.getElementById('quadrado_cinza').style.display='';
        document.getElementById('quadrado_vermelho').style.visibility='hidden';
        document.getElementById('quadrado_vermelho').style.display='none';
    } else if (itemSelecionado=="vermelho"){
        document.getElementById('azul').style.visibility='hidden';
        document.getElementById('azul').style.display='none';
        document.getElementById('cinza').style.visibility='hidden';
        document.getElementById('cinza').style.display='none';
        document.getElementById('vermelho').style.visibility='visible';
        document.getElementById('vermelho').style.display='';
        document.getElementById('quadrado_azul').style.visibility='hidden';
        document.getElementById('quadrado_azul').style.display='none';
        document.getElementById('quadrado_cinza').style.visibility='hidden';
        document.getElementById('quadrado_cinza').style.display='none';
        document.getElementById('quadrado_vermelho').style.visibility='visible';
        document.getElementById('quadrado_vermelho').style.display='';
    };
    }
</script>

 

<select name="CorFormaGeometrica" id="CorFormaGeometrica">
    <option value='azul' selected>Azul</option>
    <option value='vermelho'>Vermelho</option>
    <option value='cinza'>Cinza</option>
</select>

 

<input type="button" onClick="exibirForma()" value="Exibir"><br />

 

<img id="azul" src="azul.jpg" style="display:none; visibility:'visible'">
<img id="cinza" src="cinza.jpg" style="display:none; visibility:'visible'">
<img id="vermelho" src="vermelho.jpg" style="display:none; visibility:'visible'">

 

<div id="quadrado_azul" style="display:none; height:50px; width:50px; background-color:blue"></div>
<div id="quadrado_cinza" style="display:none; height:50px; width:50px; background-color:silver"></div>
<div id="quadrado_vermelho" style="display:none; height:50px; width:50px; background-color:red"></div>

 

Espero ter ajudado de alguma forma

 

Att.

Felipe Coutinho

Compartilhar este post


Link para o post
Compartilhar em outros sites

Então, eu queria certinho é esse script só que em vez de precisar selecionar, for por botão do teclado, o numero 1 seria verde o numero 2 vermelho e o numero 3 cinza, você consegue? e esqueci de colocar que tem que ficar em fileira os quadrados que eu por, e não carregar só um quadrado.

Compartilhar este post


Link para o post
Compartilhar em outros sites

vinicius59

Segue o código, não esqueça de agradecer a resposta e votar a favor dos nossos post.

 

<script>
function exibirFormaTecla(){
    var selecionarCor = document.getElementById("vlr_cor").value;
    if(selecionarCor==1){
        document.getElementById('quad_verde').style.visibility='visible';
        document.getElementById('quad_verde').style.display='';
    } else if (selecionarCor==2){
        document.getElementById('quad_vermelho').style.visibility='visible';
        document.getElementById('quad_vermelho').style.display='';
    } else if (selecionarCor==3){
        document.getElementById('quad_cinza').style.visibility='visible';
        document.getElementById('quad_cinza').style.display='';
    } else if (selecionarCor==4){
        document.getElementById('quad_azul').style.visibility='visible';
        document.getElementById('quad_azul').style.display='';
    } else if (selecionarCor==0){
        document.getElementById('quad_verde').style.visibility='hidden';
        document.getElementById('quad_verde').style.display='none';
        document.getElementById('quad_cinza').style.visibility='hidden';
        document.getElementById('quad_cinza').style.display='none';
        document.getElementById('quad_vermelho').style.visibility='hidden';
        document.getElementById('quad_vermelho').style.display='none';
        document.getElementById('quad_azul').style.visibility='hidden';
        document.getElementById('quad_azul').style.display='none';
    }
    document.getElementById("vlr_cor").value = document.getElementById("vlr_cor").value.substring(0,0);
};
</script>

 

<h1>Digite os números para aparecer as cores:</h1>
<h3>[ 1 - Verde | 2 - Vermelho | 3 - Cinza | 4 - Azul | 0 - Apagar ]
<input type="text" id="vlr_cor" placeholder="Pressione um número" size="20" onKeyUp="exibirFormaTecla()" autofocus></h3>
 
<table>
<tr>
<td><div
id="quad_verde" style="display:none; height:50px; width:50px; background-color:green"></div></td>
<td><div id="quad_vermelho" style="display:none; height:50px; width:50px; background-color:red"></div></td>
<td><div id="quad_cinza" style="display:none; height:50px; width:50px; background-color:silver"></div></td>
<td><div id="quad_azul" style="display:none; height:50px; width:50px; background-color:blue"></div></td>
</tr>
</table>

 

Estude o código, pois a sua necessidade é de baixa complexidade, tente fazer você colocando mais cores e mais botões.

 

Espero ter ajudado de alguma forma

 

Att.

Felipe Guedes Coutinho

Compartilhar este post


Link para o post
Compartilhar em outros sites

@Felipe Guedes Coutinho

Quando você faz a seguinte a manipulação de um elemento dessa forma:

elemento.style.display = "(table|block|inline-block|etc..)";

Você está removendo todo seu atributo style, substituindo o que existia pelo novo. Pode se feito assim também desde que as demais propriedades do elementos estejam em folha de estilo.

Quando se ataca diretamente o uma propriedade de atributo específico usamos

setAttribute('atributo', 'propriedade e valor a alterar/adicionar');

 

 

Aqui também devo ressaltar, que ficar buscando por vários elementos quando se aciona uma função não é o ideal, pois perdemos em performasse ao executar uma função. Devemos evitar ficar fazendo muitas varreduras no DOM, para melhor desempenho (lógico que em algumas situações isso é impossível).

O ideal por exemplo é buscar todos esses elementos em um pré carregamento armazena-los e então usar esse armazenamento para atacar os elementos.

 

 

@vinicius59

16 horas atrás, vinicius59 disse:

Então, eu queria certinho é esse script só que em vez de precisar selecionar, for por botão do teclado, o numero 1 seria verde o numero 2 vermelho e o numero 3 cinza, você consegue? e esqueci de colocar que tem que ficar em fileira os quadrados que eu por, e não carregar só um quadrado.

Não sei ainda se és isso que procura mas veja:

<style>
    #vermelho,
    #verde,
    #azul {
        float: left; /* Eles vão ficar um ao lado do outro */
        width: 200px;
        height: 200px;
        display: none
    }
    #vermelho.mostrar,
    #verde.mostrar,
    #azul.mostrar {
        display: block
    }
    #vermelho {background-color: red}
    #verde {background-color: green}
    #azul  {background-color: blue}
</style>

<div id="vermelho">
    Quadrado vermelho
</div>
<div id="verde">
    Quadrado verde
</div>
<div id="azul">
    Quadrado azul
</div>

<!-- Necessário lipar os dados flutuantes para correta
     orientação dos supostos novos elementos que podem
     aparecer depois dos quadrados
-->
<div style="clear: both"></div>

<script>
    // O evento keypress detecta quando uma tecla é acionada
    document.addEventListener('keypress', executaFuncao, false);

    // Armazenamos em um array quais são os elementos que vamos manipular
    var elementos = [
        document.getElementById('vermelho'), // elementos[0]
        document.getElementById('verde'), // elementos[1]
        document.getElementById('azul')      // elementos[2]
    ];

    function executaFuncao(e) {
        var key = e.keyCode;
        switch (key) {
            case 49: // Tecla 1
                elementos[0].classList.toggle('mostrar'); // Vermelho
                break;
            case 50: // Tecla 2
                elementos[1].classList.toggle('mostrar'); // Verde
                break;
            case 51: // Tecla 3
                elementos[2].classList.toggle('mostrar'); // azul
                break;

                /*
                 * // Isso está em comentário caso queria que todos
                 * // eles apareçam se qualquer uma das teclas forem
                 * // acionadas, remova a bateria de cima e deixe essa.
                 case 49: // Tecla 1
                 case 50: // Tecla 2
                 case 51: // Tecla 3
                 for (var i = 0; i < elementos.length; i++) {
                 elementos[i].classList.toggle('mostrar');
                 }
                 break;
                 */
        }
    }
</script>

Nesse exemplo usei as sequências de injeção classList.toggle, o que fará com que o elemento classificador seja adicionado quando clicado no botão ou removido caso seja acionada a tecla novamente.

Se quiser que eles continuem mesmo clicando novamente terá que modificar para:

classList.add

Nesse caso teremos que consultar se o elemento não tem o que vai adicionado caso contrário inicia o vicio HTML. 

<div class="mostrar mostrar mostrar mostrar mostrar.... Isso irá se repetir toda vez que uma das teclas forem pressionadas.

Para prevenir:

case 49: // Tecla 1
    if (!elementos[0].classList.contains('mostrar')) { // Verificamos se não tem a class "mostrar"
        elementos[0].classList.add('mostrar'); // Vermelho
    }
break;

/* ou no segunda questão */
for (var i = 0; i < elementos.length; i++) {
    if (!elementos[i].classList.contains('mostrar')) {
        elementos[i].classList.add('mostrar');
    }
}

 

 

Compartilhar este post


Link para o post
Compartilhar em outros sites

Do jeito que vocês fizeram eu só consegui colocar um quadrado de cada cor, e quando clickava dnv ele apagava, para mim se possivel é assim ('Me desculpem pelo 'spam' mas vai ter que ser assim, ok? são 5 quadrados por fileira se possivel centralizados) e a função de apagar (apague só o ultimo que foi colocado)

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

QUADRADO QUADRADO QUADRADO QUADRADO QUADRADO

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 ment0r
      Boa noite pessoal, tudo bem?
       
      Estou desenvolvendo um sistema simples com exibição de formulário via modal. Uma vez cadastrado o serviço (tabela possui apenas dois campos, id e nome), eles são exibidos numa tabela com um ícone que permite a alteração do nome.

       
      Eu clico no ícone e é chamado um modal que é gerado via ajax (pois são vários registros).
       

       
      Nesse modal é mostrado o serviço e uma vez alterado, o botão Salvar chama uma função que atualiza a tabela servico, concluindo a tarefa. Fiz o mesmo processo pra cadastrar o serviço, com a diferença de que o modal está presente na mesma página, ou seja, não é chamado via ajax.
       
      Eis os códigos:
      <a href="#" onclick="modalUpdate(<?= trim($array['id']) ?>)"> <i class='bx bx-edit'></i> </a> // Trecho onde eu chamo a função modalUpdate. Função btAltServico click:
      $('#btAltServico').click(function() { var inpnome = $('#nome'); var inpid = $('#id'); if (inpnome.val() == '') { swal("Atenção", "Por favor, preencha os campos obrigatórios", "warning"); if (inpnome.val() == '') { inpnome.css("border","2px solid #f94545"); } else { inpnome.css("border",""); } alert(inpnome); alert(inpid); } else { $.ajax({ url: '../inc/ajax/altServico.php', type: 'post', dataType: 'json', // pode ser html data: { nome : inpnome.val(), id : inpid.val() }, success: function(resposta){ if (resposta == 1) { inpnome.val(""); inpnome.css("border",""); swal("Sucesso", "Serviço alterado", "success"); } else { if (resposta == 0) { swal("Erro", "Serviço não alterado. Log de erro gerado.", "error"); } else { swal("Atenção", "Serviço já cadastrado", "warning"); } } } }) } });  
      E modalUpdate.php :
       
      <?php /* * altServico.php * * Script responsável pelo update de serviços na tabela servico * * Função chamada pelo arquivo ajax.js */ //if ($_POST) { require'../conn.php'; require'../../class/class.geral.php'; $geral = new Geral(); $nome = $_POST['nome']; $id = $_POST['nome']; $ativo = 1; // Verifica se o servico já foi cadastrado $sqlVer = "select nome from algo68_db_cliente.servico where nome = '".$nome."' and id <> ".$id.""; $queryVer = mysqli_query($conn, $sqlVer); $resultVer = mysqli_num_rows($queryVer); if ($resultVer > 0) { echo json_encode(2); // servico já cadastrado } else { // Update do servico $sql = "update algo68_db_cliente.servico set nome = '".$nome."', ativo = ".$ativo." where id = ".$id; $query = mysqli_query($conn, $sql); $result = mysqli_affected_rows($conn); if ($result > 0) { echo json_encode(1); // alterou o servico } else { $geral->logErro(date('d/m/Y|H:i:s'), @$_SERVER[REQUEST_URI], 'AlterarServico', mysqli_error($conn)); echo json_encode(0); // não alterou o servico } } //} ?> O problema é que quando clico no botão Salvar, não acontece nada - se eu colocar um alert qualquer na função click, só pra saber se está chegando, também não da nada. E está da mesma forma que o cadastro de serviço, que funciona perfeitamente.

      Bom, é isso pessoal, tentei ser o mais breve e especifico possível. Qualquer ajuda é bem vinda, obrigado a todos, desde já.
    • Por 4Unknow
      Bom dia galera.

      Estou querendo colocar um botão flutuante em meu site que acompanhe quando rolar para baixo.
      Um botão que vou utilizar para suporte.

      Um exemplo de como gostaria abaixo:


       
      Fico grato.
    • Por Kefatif
      Prezados, boa tarde!
       
      Em uma tela faço o envio de arquivos PDF para uma pasta reservada para isso.
       
      Estou tendo dificuldade para criar um botão de download na tela de consultas, quando abro a página de consulta ele está me mostrando a seguinte mensagem: "Notice: Undefined variable: row in C:\xampp\htdocs\plataforma\indicadores\consultar.php on line 126"
       
      Podem me ajudar?
       
      <?php include_once 'autenticacao.php'; include_once'../conexao.php'; ?> <!DOCTYPE html> <html lang="pt-br"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>Envio de Ata</title> <link href="../css/estilo.css" rel="stylesheet"> <!-- Bootstrap Core CSS --> <link href="../css/bootstrap.css" rel="stylesheet"> <!-- Custom CSS --> <link href="../css/modern-business.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="../font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <script src="../js/jquery.min.js"></script> </head> <body> <?php include_once 'nav-menu1.php'; ?> <!-- Page Content --> <div class="container" style="width: 90%"> <?php include_once 'cabecalho.php'; ?> <div class="row"> <?php include_once 'barra-lateral.php'; ?> <!-- Content Column --> <div class="col-md-9" style="width: 80%"> <h4><b>CONSULTAR UNIDADE</b></h4> <form class="form-inline" action="consultar.php" autocomplete="off" method="get"> <div id="form-callcenter"> <label style="width: 30%"> <input type="text" name="nome" class="form-control" placeholder="Digite o nome da unidade" style="width: 100%"> </label> <input type="submit" readonly value="Pesquisar" class="btn btn-primary"> </div> </form> <?php if (isset($_GET["nome"]) ) { $nome = $_GET["nome"]; include_once '../funcoes.php'; $sql = "select A.dt_envio, A.unidade, A.responsavel, A.observacao, A.anexo from controle_ata A where A.unidade like '%".$nome."%' order by A.dt_envio desc"; $result = mysqli_query($con, $sql); if (mysqli_num_rows($result) > 0) { ?> <table class="table table-hover table-bordered" id="tabela-dispensacao2"> <tr> <th>Unidade</th> <th>Data do envio</th> <th>Responsável</th> <th>Observação</th> <th>Ata</th> <th>Download</th> </tr> <?php if($row["anexo"] == ''){ $cor = "red"; }else{ $cor = "blue"; } while ($row = mysqli_fetch_array($result)){ foreach($row as $key => $values){ $row[$key]= utf8_encode($values); } ?> <tr> <td><?php echo $row["unidade"]?></td> <td><?php echo dataTela($row["dt_envio"]); ?></td> <td><?php echo $row["responsavel"]; ?></td> <td><?php echo $row["observacao"] ?></td> <td><?php echo $row["anexo"] ?></td> <td><a class="<?php if($row["ANEXO"] == ''){echo "link-nao-ativo";}?>" href='anexos/<?php echo $row["ANEXO"] ?>' target="_blank"> <i style="color:<?php echo $cor ?>" class="glyphicon glyphicon-download-alt"></i> </a> </td> </tr> <?php }//ENCERRANDO O WHILE ?> </table> <?php }else{ echo "Nenhuma unidade encontrada!<br>"; } } ?> <?php mysqli_close($con); ?> </div> </div> <!-- /.row --> </div> <!-- /.container --> <!-- jQuery --> <script src="../js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="../js/bootstrap.min.js"></script> </body> </html>  
       
      Agradeço a ajuda desde já!
    • Por janir.matheus
      Bom dia,
       
      Preciso de ajuda ajuda para resolver o problema de SIGSEGV, basicamente tennho um zconection dentro de uma classe e recebo erro quando tento acessá-lo. Segue um trecho da classe:
      unit unt_classconexao; {$mode objfpc}{$H+} interface uses Classes, SysUtils, ZConnection, ZDataset; type { tConexao } tConexao = class private public vConector : TZConnection; function Listar_Usuarios:TZReadOnlyQuery; procedure Conectar_Banco; end; implementation { tConexao } function tConexao.Listar_Usuarios: TZReadOnlyQuery; var zrquery : TZReadOnlyQuery; begin Conectar_Banco; try zrquery := TZReadOnlyQuery.Create(nil); zrquery.Connection := vConector; zrquery.SQL.Clear; zrquery.SQL.Text := 'SELECT * from tbl_profissionais'; zrquery.Open; Listar_Usuarios := zrquery; finally end; end; procedure tConexao.Conectar_Banco; begin //vConector := TZConnection.Create(nil); vConector.HostName := 'localhost'; vConector.Port := 3306; vConector.Database := 'Caps'; vConector.Protocol := 'mysql-5'; vConector.User := 'root'; vConector.Password := ''; vConector.Connected := true; end; end. Após isso tento fazer uso dessa classe para popular um DBGrid:
      unit unt_frmprincipal; {$mode objfpc}{$H+} interface uses Classes, SysUtils, DB, Forms, Controls, Graphics, Dialogs, Menus, DBGrids, ZConnection, unt_classconexao; type { Tfrm_principal } Tfrm_principal = class(TForm) DataSource1: TDataSource; DBGrid1: TDBGrid; MainMenu_frmPrincipal: TMainMenu; MenuItem_AplicativoSair: TMenuItem; N1: TMenuItem; MenuItem_AplicativoLogin: TMenuItem; MenuItem_Aplicativo: TMenuItem; procedure MenuItem_AplicativoLoginClick(Sender: TObject); private public vConexao : tConexao; end; var frm_principal: Tfrm_principal; implementation {$R *.lfm} { Tfrm_principal } procedure Tfrm_principal.MenuItem_AplicativoLoginClick(Sender: TObject); begin //vConexao := tConexao.Create; DataSource1.DataSet := vConexao.Listar_Usuarios; end; end. A mensagem de erro que recebo dá a entender que o problema ocorre logo que o zconnection começa a ser configurado, como vocês podem ver pelos trechos comentados eu tentei instanciar o componente também sem sucesso. Não tenho experiencia com POO e tenho certeza que estou cometendo um erro bobo, então peço uma explicação sobre como resolver isso. Agradeço de antemão a quem puder me ajudar.
       
      PS. Estou usando o Lazarus.
    • Por 4Unknow
      Boa noite comunidade da Imasters, como vocês estão?

      Pessoal peguei um botão responsivo com popup, mas não consigo adicionar mais dele um do lado do outro.
      Vou deixar o conteúdo dele aqui se alguém puder me dar uma luz. Só queria copiar ele para adicionar mais dois botões um ao lado do outro.

      Quem puder me ajudar, ficaria agradecido.

      segue código:

      index.html:
       
      <!DOCTYPE html> <html lang="en" > <head> <meta charset="UTF-8"> <title>Alterações Robô Everest</title> <link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css'><link rel="stylesheet" href="./style.css"> </head> <body> <!-- partial:index.partial.html --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" integrity="sha384-DNOHZ68U8hZfKXOrtjWvjxusGo9WQnrNx2sqG0tfsghAvtVlRW3tvkXWZh58N9jp" crossorigin="anonymous"> <h1> Configurações Robô Everest </h1> <h2> Data: 14/04/2021</h2> <button type="button" class="main-btn-rect popup-btn" data-popup="popup-reg">Modo Agressivo</button> <div id="popup-reg" class="popup"> <div class="popup-content"> <div class="event-header"> <h6>Don't be shy, say hi!</h6> </div> Stop Loss: 255<br> Stop Gain: 30<br><br> Ou a seu gosto!<br><br> Desvio Envelope: 0.12<br><br> Pausas nas operações: 10:00,11:00,10:30,12:30<br> <span class="fade-out main-btn-circle">╳</span> </div> </div> <!-- partial --> <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script><script src="./script.js"></script> </body> </html>
      script.js:
       
      $(document).ready(function(){ $('.popup-btn').click(function(){ var popupBlock = $('#'+$(this).data('popup')); popupBlock.addClass('active') .find('.fade-out').click(function(){ popupBlock.css('opacity','0').find('.popup-content').css('margin-top','350px'); setTimeout(function(){ $('.popup').removeClass('active'); popupBlock.css('opacity','').find('.popup-content').css('margin-top',''); }, 600); }); }); });
      style.css:
       
      @import url('https://fonts.googleapis.com/css?family=Lobster'); @import url('https://fonts.googleapis.com/css?family=Roboto'); body{ margin: 0; padding: 0; height: 100vh; font-family: 'RobotoLight', sans-serif; border-bottom: 1px solid #FFFFF0; background: #00c6ff; background: -webkit-linear-gradient(to right, #0072ff, #00c6ff); background: linear-gradient(to right, #0072ff, #00c6ff); overflow: hidden; } button { text-decoration: none; border: none; } h1 { position: absolute; display: inline-table; top: 20%; left: 50%; transform: translate(-50%, -50%); font-size: 30px; text-transform: uppercase; letter-spacing: 2px; color: #FFFFF0; } h2 { position: absolute; top: 35%; left: 50%; transform: translate(-50%, -50%); font-size: 25px; text-align: center; color: #FFFFF0; } .popup-btn{ position: absolute!important; top: 55%; left: 50%; transform: translate(-50%,-50%); } .main-btn-rect, .main-btn-circle{ position: relative; margin: 0; font-family: 'Roboto', sans-serif; color: #FFFFF0; background-color: rgb(252, 79, 79); text-transform: uppercase; font-size: 25px; letter-spacing: 1px; outline: none; cursor: pointer; z-index: 100; } .main-btn-rect { padding: 10px 80px; line-height: 30px; } .main-btn-rect:before, .main-btn-rect:after{ position: absolute; content: ''; top:0; width: 0%; height: 100%; background-color: rgba(255, 255, 240, 0.2); -webkit-transition: width 0.3s; -o-transition: width 0.3s; transition: width 0.3s; } .main-btn-rect:before { left: 0; } .main-btn-rect:after { right: 0; } .main-btn-rect:hover:before, .main-btn-rect:hover:after{ width: 50%; } .main-btn-circle{ height: 40px; width: 40px; -webkit-border-radius: 50%; border-radius: 100%; line-height: 40px; -webkit-transition: box-shadow 0.3s; -o-transition: box-shadow 0.3s; transition: box-shadow 0.3s; } .main-btn-circle:hover{ -webkit-box-shadow: inset 2px 1px 0px 20px rgba(255, 255, 240, 0.2); -moz-box-shadow: inset 2px 1px 0px 20px rgba(255, 255, 240, 0.2); box-shadow: inset 2px 1px 0px 20px rgba(255, 255, 240, 0.2); } .popup{ position: fixed; top: 100%; width: 100%; height: 100%; z-index: 10001; } .popup.active{ top:0; background-color: rgba(3, 3, 3, 0.98); transition: background-color .6s ,opacity .6s; } .popup .main-btn-rect{ padding: 10px 100px; } .popup .popup-content{ position: absolute; top: 50%; left: 50%; max-height: 568px; min-width: 320px; margin-top: 150px; padding: 25px; background-color: #FFFFF0; color: #070000; -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); -ms-transform: translateX(-50%) translateY(-50%); transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); -moz-transform: translateX(-50%) translateY(-50%); -o-transform: translateX(-50%) translateY(-50%); transition: margin .6s; -webkit-transition: margin .6s; -moz-transition: margin .6s; -o-transition: margin .6s; } .popup.active .popup-content{ margin-top: 0px; } .popup-content h6{ display: table; font-size: 16px; text-align: center; margin: 10px auto; font-family: 'Roboto',sans-serif; text-transform: uppercase; font-weight: 100; } .form-group{ position: relative; width: 90%; margin: 0px auto; } form#send input, form#send textarea{ position: relative; margin-bottom: 32px; width: 100%; height: 29px; font-family: 'RobotoLight', sans-serif; text-indent: 20px; background-color: transparent; outline: 0; border: none; border-bottom: 1px solid #070000; -webkit-transition: border 0.6s; -o-transition: border 0.6s; transition: border 0.6s; } form#send input:focus, form#send textarea:focus{ border-bottom: 1px solid rgb(63, 173, 168); } form#send label{ position: absolute; top: 0; line-height: 28px; -webkit-transition: color .5s; -o-transition: color .5s; transition: color .5s; } form#send input:focus + label, form#send textarea:focus + label{ color: rgb(63, 173, 168); } form#send .txt{ line-height: 22px; left: 2px; } form#send .main-btn-rect { position: relative; display: block; padding: 12px 80px; margin: 0px auto; font-size: 14px; } form#send .main-btn-rect i { margin-right: 5px; } .popup .fade-out{ position: absolute; top: -20px; right: -20px; text-align: center; font-size: 15px; } .share-wrap{ position: absolute; display: inline-table; top: 67%; left: 50%; transform: translate(-50%, -50%); padding: 15px; text-align: center; } .share-btn{ color: #FFFFF0; padding: 7px 25px; text-decoration: none; cursor: pointer; font-weight: 100; font-size: 14px; font-family:'Lobster', sans-serif; background-color: rgba(63, 173, 168, .8); text-transform: uppercase; border-radius: 5px; transition: background-color .5s; -webkit-transition: background-color .5s; -moz-transition: background-color .5s; -o-transition: background-color .5s; } .share-btn:hover{ color: #FFFFF0; text-decoration: none; background-color: rgba(63, 173, 168, 1.0); } .resp-sharing-button__link, .resp-sharing-button__icon { display: inline-block } .resp-sharing-button__link { text-decoration: none; color: #fff; margin: 2px; } .resp-sharing-button { border-radius: 5px; transition: 25ms ease-out; padding: 6px 9px; transition: background-color .5s; -webkit-transition: background-color .5s; -moz-transition: background-color .5s; -o-transition: background-color .5s; } .resp-sharing-button__icon svg { width: 1em; height: 1em; margin-right: 0.4em; vertical-align: top } .resp-sharing-button--small svg { margin: 0; vertical-align: middle } .resp-sharing-button__icon, .resp-sharing-button__icon--solid, .resp-sharing-button__icon--solidcircle { fill: #fff; stroke: none } .resp-sharing-button--facebook { background-color: #3b5998; border-color: #3b5998; } .resp-sharing-button--facebook:hover, .resp-sharing-button--facebook:active { background-color: #2d4373; border-color: #2d4373; } .resp-sharing-button--twitter { background-color: #55acee; border-color: #55acee; } .resp-sharing-button--twitter:hover, .resp-sharing-button--twitter:active { background-color: #2795e9; border-color: #2795e9; } .resp-sharing-button--linkedin { background-color: #0077b5; border-color: #0077b5; } .resp-sharing-button--linkedin:hover, .resp-sharing-button--linkedin:active { background-color: #046293; border-color: #046293; } @media only screen and (max-width: 768px){ h1 {font-size: 25px;} h2 {font-size: 14px;} form#send .main-btn-rect {padding: 7px 60px; font-size: 14px;} .popup-btn{padding: 7px 60px; font-size: 14px;} } Tentei copiar o código do index.html mas não aparece os outros botões.
      Puderem me ajudar agradeço.

      Um abraço.
×

Informação importante

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